You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PIL生成等距对角线?旋转后无黑边且支持多色

需求与问题

需要使用PIL生成等距的对角线图案。当前实现方式是先绘制水平等宽色块,再将图像旋转45度,但旋转后出现以下问题:

  • 线条尺寸不足,出现黑边
  • 无法保持对角线的等距性
  • 需要支持更多颜色的扩展
当前实现代码
# 原代码遗漏PIL模块导入,补充后可正常运行
from PIL import Image, ImageDraw
import random

im = Image.new('RGB', (1000, 1000), (255, 255, 255))
draw = ImageDraw.Draw(im)
colors = [(255,0,255), (0,0,255)]
random.shuffle(colors)
length = len(colors)
amount = 1000 / length
x1 = 0
y1 = 0
x2 = 1000
y2 = 0
for color in colors:
    shape = [(x1, y1 + amount // 2), (x2, y2 + amount // 2)]
    draw.line(shape, fill=color, width=int(amount))
    y1 += amount
    y2 += amount

im.save("pre_diagonal.png")
colorimage = Image.open('pre_diagonal.png')
# 原代码未完成旋转调用,应为类似 colorimage.rotate(45, expand=True) 的形式
out = colorimage.rotate
效果展示
  • 旋转前效果:处理前效果
  • 旋转后效果:旋转后效果

内容的提问来源于stack exchange,提问作者Mashu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 22:48:17