Search code examples
pythonpython-imaging-librarygeneratordrawaggdraw

Python not working to draw a hexagon using PIL and aggdraw


My code is as follows, but it does not work out as expected to draw a hexagon, with no hexagon and error either.

import math
from PIL import Image
from aggdraw import Draw, Brush, Pen


def hexagon_generator(edge_length, offset):
    """Generator for coordinates in a hexagon."""
    x, y = offset
    for angle in range(0, 360, 60):
        x += math.cos(math.radians(angle)) * edge_length
        y += math.sin(math.radians(angle)) * edge_length
        yield int(x)
        yield int(y)


def main():
    image = Image.new('RGB', (1000, 1000), 'white')
    draw = Draw(image)
    hexagon = hexagon_generator(40, offset=(30, 15))
    print(list(hexagon))
    draw.polygon(list(hexagon), Pen('black'), Brush('red'))

Solution

  • hexagon_generator creates a generator - the elements of hexagon can only be iterated through once, after which it is "exhausted". When you call print(list(hexagon)) this takes all elements from the iterator you created in the previous line, and thus when you write list(hexagon) again in the next line, this creates an empty list.

    Cast it directly to a list to solve this issue (not printing it would work too):

    def main():
        image = Image.new('RGB', (1000, 1000), 'white')
        draw = Draw(image)
        hexagon = list(hexagon_generator(40, offset=(30, 15)))
        print(hexagon)
        draw.polygon(hexagon, Pen('black'), Brush('red'))