Mig*_*uel 2 python python-imaging-library pillow
从PIL文档中:
PIL.ImageDraw.Draw.line(xy,fill = None,width = 0)
在xy列表中的坐标之间绘制一条线。
参数:
- xy –由[[x,y),(x,y),...]等2元组或[x,y,x,y,...]等数值组成的序列。
- fill –用于行的颜色。
- width –线宽,以像素为单位。请注意,线连接处理不当,因此宽的折线看起来不太好。
我正在寻找解决此问题的方法。对我来说,一个好的解决方案是使线由PIL.ImageDraw圆角的末端(capstylein TKinter)绘制。有对应的PIL.ImageDraw吗?
最小的工作示例:
from PIL import Image, ImageDraw
WHITE = (255, 255, 255)
BLUE = "#0000ff"
MyImage = Image.new('RGB', (600, 400), WHITE)
MyDraw = ImageDraw.Draw(MyImage)
MyDraw.line([100,100,150,200], width=40, fill=BLUE)
MyDraw.line([150,200,300,100], width=40, fill=BLUE)
MyDraw.line([300,100,500,300], width=40, fill=BLUE)
MyImage.show()
Run Code Online (Sandbox Code Playgroud)
MWE的结果:
有标准选项joint='curve'的的ImageDraw.line设计来解决它。
您的示例可能看起来像
from PIL import Image, ImageDraw
WHITE = (255, 255, 255)
BLUE = "#0000ff"
MyImage = Image.new('RGB', (600, 400), WHITE)
MyDraw = ImageDraw.Draw(MyImage)
line_points = [(100, 100), (150, 200), (300, 100), (500, 300)]
MyDraw.line(line_points, width=40, fill=BLUE, joint='curve')
MyImage.show()
Run Code Online (Sandbox Code Playgroud)
需要特别注意端点,但接头是固定的。
结果:
小智 3
我和你有同样的问题。但是,您可以通过简单地绘制一个与每个顶点的线宽相同直径的圆来轻松解决该问题。下面是您的代码,稍加修改即可解决问题
from PIL import Image, ImageDraw
WHITE = (255, 255, 255)
BLUE = "#0000ff"
RED = "#ff0000"
MyImage = Image.new('RGB', (600, 400), WHITE)
MyDraw = ImageDraw.Draw(MyImage)
# Note: Odd line widths work better for this algorithm,
# even though the effect might not be noticeable at larger line widths
LineWidth = 41
MyDraw.line([100,100,150,200], width=LineWidth, fill=BLUE)
MyDraw.line([150,200,300,100], width=LineWidth, fill=BLUE)
MyDraw.line([300,100,500,300], width=LineWidth, fill=BLUE)
Offset = (LineWidth-1)/2
# I have plotted the connecting circles in red, to show them better
# Even though they look smaller than they should be, they are not.
# Look at the diameter of the circle and the diameter of the lines -
# they are the same!
MyDraw.ellipse ((150-Offset,200-Offset,150+Offset,200+Offset), fill=RED)
MyDraw.ellipse ((300-Offset,100-Offset,300+Offset,100+Offset), fill=RED)
MyImage.show()
Run Code Online (Sandbox Code Playgroud)