使用ImageDraw绘制箭头形状的实例代码
import PIL.ImageDraw as ImageDraw
import PIL.Image as Image
def draw_arrow(image, start, end, color, width):
# 创建一个ImageDraw对象
draw = ImageDraw.Draw(image)
# 计算箭头的一半宽度
half_width = width // 2
# 计算箭头开始和结束点的方向向量
direction_vector = (end[0] - start[0], end[1] - start[1])
# 计算箭头结束点
arrow_end = (end[0] - direction_vector[0]/2, end[1] - direction_vector[1]/2)
# 计算箭头两侧的点
side1 = (arrow_end[0] + half_width*direction_vector[1]/max(abs(direction_vector[0]), abs(direction_vector[1])),
arrow_end[1] - half_width*direction_vector[0]/max(abs(direction_vector[0]), abs(direction_vector[1])))
side2 = (arrow_end[0] - half_width*direction_vector[1]/max(abs(direction_vector[0]), abs(direction_vector[1])),
arrow_end[1] + half_width*direction_vector[0]/max(abs(direction_vector[0]), abs(direction_vector[1])))
# 绘制箭头线段
draw.line([start, end], fill=color, width=width)
# 绘制箭头两侧的线段
draw.line([end, side1], fill=color, width=width)
draw.line([end, side2], fill=color, width=width)
# 创建一个黑色背景的Image对象
image = Image.new("RGB", (500, 500), "black")
draw = ImageDraw.Draw(image)
# 绘制一个箭头形状
arrow_start = (100, 100)
arrow_end = (400, 400)
arrow_color = "red"
arrow_width = 5
draw_arrow(image, arrow_start, arrow_end, arrow_color, arrow_width)
# 保存绘制结果
image.save("arrow.png")
image.show()
