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

如何在Pillow中绘制沿Y轴递增方向从深绿到酸橙绿渐变的线条?

在Pillow中绘制Y轴渐变线条

Pillow原生的ImageDraw.line()方法不支持直接传入渐变颜色参数,我们可以自定义一个函数来实现你想要的效果,参数格式完全匹配你给出的示例:

实现方案

  1. 将颜色名称转换为RGB数值,便于进行渐变插值计算
  2. 以线条在Y轴方向的总跨度作为渐变基准,计算每个点的颜色过渡比例
  3. 遍历线条路径上的每个点,根据当前Y坐标的相对位置生成对应颜色
  4. 通过绘制小矩形模拟带宽度的平滑渐变线条

完整代码

from PIL import Image, ImageDraw, ImageColor
import math

def draw_gradient_line(draw, points, width=1, start_color='darkgreen', end_color='lime', gradient_based_on='+y'):
    # 把颜色名称转为RGB元组
    start_rgb = ImageColor.getrgb(start_color)
    end_rgb = ImageColor.getrgb(end_color)
    
    (p1x, p1y), (p2x, p2y) = points
    # 计算Y轴方向的总差值,作为渐变的计算基准
    total_y_diff = abs(p2y - p1y)
    
    if total_y_diff == 0:
        # Y坐标无变化,直接绘制单色线条
        draw.line(points, width=width, fill=start_color)
        return
    
    # 控制线条平滑度的步长,数值越小线条越细腻
    step = 0.5
    # 计算需要绘制的点的数量
    num_steps = int(math.hypot(p2x - p1x, p2y - p1y) / step)
    
    for i in range(num_steps + 1):
        # 计算当前点的坐标
        t = i / num_steps
        x = p1x + t * (p2x - p1x)
        y = p1y + t * (p2y - p1y)
        
        # 根据Y坐标的相对位置计算渐变比例(向下移动时Y递增,比例从0到1)
        if p2y > p1y:
            ratio = (y - p1y) / total_y_diff
        else:
            # 若线条向上,反向计算比例(保持颜色过渡逻辑一致)
            ratio = (p1y - y) / total_y_diff
        
        # 插值计算当前点的RGB颜色
        r = int(start_rgb[0] + ratio * (end_rgb[0] - start_rgb[0]))
        g = int(start_rgb[1] + ratio * (end_rgb[1] - start_rgb[1]))
        b = int(start_rgb[2] + ratio * (end_rgb[2] - start_rgb[2]))
        current_color = (r, g, b)
        
        # 绘制带宽度的点(用矩形模拟,避免细线条的锯齿)
        half_width = width / 2
        draw.rectangle(
            [(x - half_width, y - half_width), (x + half_width, y + half_width)],
            fill=current_color
        )

# 使用示例
if __name__ == "__main__":
    img = Image.new('RGB', (1024, 800), 'white')
    draw = ImageDraw.Draw(img)
    
    # 调用自定义函数绘制渐变线条
    draw_gradient_line(
        draw,
        [(200, 100), (800, 700)],
        width=2,
        start_color='darkgreen',
        end_color='lime',
        gradient_based_on='+y'
    )
    
    img.save('gradient_line.png')

关键说明

  • 函数参数完全匹配你给出的示例,直接替换原生draw.line即可使用
  • 步长step可根据需求调整,0.5的数值平衡了绘制速度和平滑度
  • 处理了Y坐标无变化的边界场景,避免除以零错误
  • 渐变逻辑严格基于Y坐标的递增,从起始点向下移动时颜色从深绿逐步过渡到酸橙绿

内容的提问来源于stack exchange,提问作者Muhammad Ikhwan Perwira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 06:53:26