Python PIL:如何绘制自定义填充多边形

时间:2020-06-16 07:19:06

标签: python-3.x image-processing python-imaging-library

我想知道pillow中是否有一种方法可以绘制自定义填充的多边形,我知道我可以绘制矩形和圆形,那么自定义多边形呢?

具体来说,我想绘制如下图所示的内容: example img

任何想法,我如何实现这一目标。谢谢

1 个答案:

答案 0 :(得分:0)

我并不以自己的图形设计能力或耐心修整美学而著称,但这应该可以给您一个想法:

#!/usr/bin/env python3

from PIL import Image, ImageDraw

# Form basic purple image without alpha
w, h = 700, 250
im = Image.new('RGB', (w,h), color=(66,0,102))

# Form alpha channel independently
alpha = Image.new('L', (w,h), color=0)

# Get drawing context
draw   = ImageDraw.Draw(alpha)
radius = 50
hline  = h-radius
OPAQUE, TRANSPARENT = 255, 0
# Draw white where we want opaque
draw.rectangle((0,0,w,hline), fill=OPAQUE)
draw.ellipse((w//2-radius,hline-radius,w//2+radius,h), fill=OPAQUE) 

# Draw black where we want transparent
draw.ellipse(((w//3)-radius,-radius,(w//3)+radius,radius), fill=TRANSPARENT)
draw.ellipse(((2*w//3)-radius,-radius,(2*w//3)+radius,radius), fill=TRANSPARENT)

# DEBUG only - not necessary
alpha.save('alpha.png')

# Put our shiny new alpha channel into our purple background and save
im.putalpha(alpha)
im.save('result.png')

enter image description here

alpha通道看起来像这样-我人为地添加了一个红色边框,因此您可以看到它的范围:

enter image description here

相关问题