PIL rectangle
不支持这个width
论点.
这是一个绘制第一个初始矩形的方法,然后是向内的其他矩形 - 注意,线宽不沿边框居中.
def draw_rectangle(draw, coordinates, color, width=1): for i in range(width): rect_start = (coordinates[0][0] - i, coordinates[0][1] - i) rect_end = (coordinates[1][0] + i, coordinates[1][1] + i) draw.rectangle((rect_start, rect_end), outline = color) # example usage im = Image.open(image_path) drawing = ImageDraw.Draw(im) top_left = (50, 50) bottom_right = (100, 100) outline_width = 10 outline_color = "black" draw_rectangle(drawing, (top_left, bottom_right), color=outline_color, width=outline_width)
除了四条线之外,您还可以绘制一条包含四个点的线,从而形成一个矩形:
def drawrect(drawcontext, xy, outline=None, width=0):
(x1, y1), (x2, y2) = xy
points = (x1, y1), (x2, y1), (x2, y2), (x1, y2), (x1, y1)
drawcontext.line(points, fill=outline, width=width)
# example
from PIL import Image, ImageDraw
im = Image.new("RGB", (150, 150), color="white")
draw = ImageDraw.Draw(im)
drawrect(draw, [(50, 50), (100, 100)], outline="red", width=5)
im.show()