如何用PIL绘制等宽垂直线与斜线?已有水平线实现代码
使用PIL绘制等宽垂直线与斜线
问题背景
已通过PIL实现等宽水平线的绘制,现在需要完成等宽垂直线与斜线的绘制。
原水平线实现代码
from PIL import Image, ImageDraw import random im = Image.new('RGB', (1000, 1000), (255, 255, 255)) draw = ImageDraw.Draw(im) colors = [(255,0,0), (255,255,0), (255,0,255)] random.shuffle(colors) length = len(colors) amount = 1000 / length x1 = 0 y1 = 0 x2 = 0 y2 = 1000 for color in colors: shape = [(x1 + amount, y1 // 2), (x2 + amount, y2 // 2)] draw.line(shape, fill=color, width=int(amount)) x1 += amount x2 += amount im.save('horizontal_lines.png')
等宽垂直线实现代码
垂直线的绘制逻辑和水平线对称,只需调整线段坐标为垂直方向,通过宽度参数控制色块宽度:
from PIL import Image, ImageDraw import random im = Image.new('RGB', (1000, 1000), (255, 255, 255)) draw = ImageDraw.Draw(im) colors = [(255,0,0), (255,255,0), (255,0,255)] random.shuffle(colors) length = len(colors) amount = 1000 / length y1 = 0 x1 = 0 y2 = 0 x2 = 1000 for color in colors: # 垂直线段垂直贯穿画布,沿水平方向分布 shape = [(x1 // 2, y1 + amount), (x2 // 2, y2 + amount)] draw.line(shape, fill=color, width=int(amount)) y1 += amount y2 += amount im.save('vertical_lines.png')
等宽斜线实现代码
斜线若用line的width参数很难保证视觉等宽,建议绘制闭合多边形填充斜向区域,以45度斜向分割为例:
from PIL import Image, ImageDraw import random import math im = Image.new('RGB', (1000, 1000), (255, 255, 255)) draw = ImageDraw.Draw(im) colors = [(255,0,0), (255,255,0), (255,0,255)] random.shuffle(colors) length = len(colors) # 按画布对角线长度计算每个斜向区域的宽度 diagonal_length = math.hypot(1000, 1000) amount = diagonal_length / length # 45度斜线的方向向量比例 dx = 1000 / diagonal_length dy = 1000 / diagonal_length current_offset = 0 for color in colors: # 构建斜向区域的多边形顶点 polygon = [ (current_offset * dx, 0), (1000, 1000 - current_offset * dy), (1000 - (current_offset + amount) * dx, 1000), (0, (current_offset + amount) * dy) ] draw.polygon(polygon, fill=color) current_offset += amount im.save('diagonal_lines.png')
补充说明
- 垂直线与水平线逻辑对称,仅调整了线段的延伸方向;
- 斜线采用多边形填充,能精准保证每个斜向区域的视觉宽度一致,避免单纯画线带来的宽度偏差。
内容的提问来源于stack exchange,提问作者Mashu
相关产品推荐
相关产品推荐

