0

Is it possible to dynamically draw a polygon of N-sides with rounded corners? I've seen examples done for rectangles/squares, but not for other polygons. I can easily draw the polygon, but I'm looking to achieve a rounded affect for each corner. Any help is greatly appreciated!

from PIL import Image, ImageDraw

#Triangle
inset = 40
W, H = (300,300)
# Create empty black canvas
im = Image.new('RGBA', (W, H), '#558353')

# Draw polygon
draw = ImageDraw.Draw(im)
draw.polygon([(W/2,inset), (W-inset, H-inset), (inset,H-inset)], fill = 'black')

im.show()

Output:

Output

Desired (created in Lucid Chart):

enter image description here

alpacafondue
  • 353
  • 3
  • 16

1 Answers1

0

Here's my best shot at it. The ImageDraw rasterizer isn't so good at drawing wide lines. I had to fudge the line width (with +2) to make it look a little better.

from PIL import Image, ImageDraw
import operator

def vadd(a, b):
    """ Vector addition. """
    return tuple(map(operator.add, a, b))

#Triangle
inset = 40
W, H = (300,300)
# Create empty black canvas
im = Image.new('RGBA', (W, H), '#558353')

# Draw polygon
draw = ImageDraw.Draw(im)

# Vertices of the polygon.
v = [
    (inset, H-inset),
    (W-inset, H-inset),
    (W/2, inset) ]


# Radius of rounded corner.
r = 10
d = 2*r

# Outline of the polygon.
[ draw.line((v[i], v[i+1]), fill='black', width=d+2) for i in range(len(v)-1) ]
draw.line((v[-1], v[0]), fill='black', width=d+2)

# Draw a circle centered on each vertex.
for corner in v:
    c = [vadd(corner, (-r, -r)), vadd(corner, (r, r))]
    draw.pieslice(c, 0, 360, 'black') 

# Now fill in the middle.
ImageDraw.floodfill(im, (W/2, H/2), (0, 0, 0))

im.show()

Image Result

Rusty Widebottom
  • 985
  • 2
  • 5
  • 14
  • https://i.imgur.com/EWK56Xh.png is what gets produced for me, but this is definitely on the right track. Thanks! – alpacafondue Apr 26 '20 at 17:39
  • Ah darn. Yeah, [the documentation for floodfill](https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html#PIL.ImageDraw.PIL.ImageDraw.floodfill) has a warning that says that method is experimental. – Rusty Widebottom Apr 26 '20 at 18:19