三角形三个顶点的颜色分别为红、绿、蓝,使用有效边表算法填充三角,要求三角形线条平滑,颜色填充满整个图形,渐变色流畅肉眼看不出瑕疵,生成完整python代码。
时间: 2024-12-02 19:17:33 浏览: 49
在Python中,我们可以使用`PIL`库(Python Imaging Library)配合`numpy`来进行颜色填充,并利用`Bresenham线`算法绘制平滑的三角形。以下是一个简单的示例代码:
```python
from PIL import Image, ImageDraw
import numpy as np
# 定义三角形的顶点坐标
vertices = [(0, 0), (500, 0), (250, 400)] # 红色(0, 0), 绿色(500, 0), 蓝色(250, 400)
def draw_triangle(image, vertices, start_color, end_color):
# 初始化画布和画笔
draw = ImageDraw.Draw(image)
gradient = np.linspace(start_color, end_color, 256) # 创建渐变数组
def bresenham(x1, y1, x2, y2):
dx = abs(x2 - x1)
dy = abs(y2 - y1)
steep = abs(dy) > dx
if steep:
x1, y1 = y1, x1
x2, y2 = y2, x2
swapped = False
if x1 > x2:
x1, x2 = x2, x1
swapped = True
dx, dy = x2 - x1, 1 if y1 < y2 else -1
err = dx / 2
y = y1
for x in range(x1, x2 + 1):
if steep:
draw.point((y, x), color=tuple(int(i) for i in gradient[int(err)]))
else:
draw.point((x, y), color=tuple(int(i) for i in gradient[int(err)]))
err += dy
if swapped:
draw.point((y2, x2), color=tuple(int(i) for i in gradient[int(err)]))
# 使用Bresenham算法绘制三角形
for vertex in zip(vertices, vertices[1:] + [vertices[0]]):
bresenham(*vertex)
# 创建图像
width, height = 800, 600
image = Image.new('RGB', (width, height), 'white')
draw_triangle(image, vertices, (255, 0, 0), (0, 255, 0)) # 将红色渐变为绿色
# 显示和保存图像
image.show()
image.save('triangle_gradient.png')
阅读全文