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

Python中如何为PNG图片添加虚线或点线?

PNG图片绘制虚线/点线实现方案

你当前使用Pillow库生成PNG的基础代码仅完成了画布创建和保存,没有绘制线条的逻辑,且Pillow原生的线条绘制方法默认仅支持实线,可通过自定义分段绘制的方式实现虚线、点线效果,无需安装额外依赖。

原有代码问题说明

你写的Windows路径存在转义错误:路径中的\在Python字符串中会被识别为转义字符,需要替换为双反斜杠\\或者使用原始字符串,否则会触发路径找不到的报错。

可直接复用的实现代码

from PIL import Image, ImageDraw

def draw_dashed_line(draw_ctx, start_pos, end_pos, line_color, line_width=1, dash_len=10, gap_len=5):
    """
    绘制任意角度的虚线/点线
    :param draw_ctx: ImageDraw绘图上下文对象
    :param start_pos: 线条起点,格式为(x, y)元组
    :param end_pos: 线条终点,格式为(x, y)元组
    :param line_color: 线条颜色,RGB元组格式
    :param line_width: 线条宽度,单位像素
    :param dash_len: 虚线实心段长度,单位像素;设为1~3即可实现点线效果
    :param gap_len: 虚线/点线的空白间隔长度,单位像素
    """
    x1, y1 = start_pos
    x2, y2 = end_pos
    total_len = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
    # 计算线条方向的单位向量
    unit_x = (x2 - x1) / total_len
    unit_y = (y2 - y1) / total_len

    cur_x, cur_y = x1, y1
    cur_offset = 0
    while cur_offset < total_len:
        # 绘制当前实心段
        seg_end_x = cur_x + unit_x * min(dash_len, total_len - cur_offset)
        seg_end_y = cur_y + unit_y * min(dash_len, total_len - cur_offset)
        draw_ctx.line((cur_x, cur_y, seg_end_x, seg_end_y), fill=line_color, width=line_width)
        # 跳过空白间隔,移动到下一个实心段起点
        cur_offset += dash_len + gap_len
        cur_x = x1 + unit_x * cur_offset
        cur_y = y1 + unit_y * cur_offset

# 调用示例
if __name__ == "__main__":
    hex_color = "ffffff"  # 替换为你实际使用的画布底色十六进制值
    legend_code = "demo"  # 替换为你实际的文件名变量
    # 创建画布
    im = Image.new(
        'RGB',
        (2000, 2000),
        tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
    )
    draw_ctx = ImageDraw.Draw(im)
    # 绘制普通虚线:实心段10px,间隔5px,黑色3px宽
    draw_dashed_line(
        draw_ctx,
        start_pos=(100, 200),
        end_pos=(1900, 200),
        line_color=(0, 0, 0),
        line_width=3,
        dash_len=10,
        gap_len=5
    )
    # 绘制点线:实心段2px,间隔6px,红色2px宽
    draw_dashed_line(
        draw_ctx,
        start_pos=(100, 500),
        end_pos=(1900, 500),
        line_color=(255, 0, 0),
        line_width=2,
        dash_len=2,
        gap_len=6
    )
    print("...Saving...")
    # 路径已做转义处理,可正常保存
    im.save(f'C:\\Users\\th3m1s\\Desktop\\Lejant\\{legend_code}.png', quality=100)

参数调整说明

  • 要实现方点样式的点线,将dash_len设为1~3像素,根据视觉需要调整gap_len即可
  • 要实现圆点样式的点线,把函数内绘制实心段的draw_ctx.line替换为draw_ctx.ellipse绘制小圆形即可
  • 函数支持任意角度的斜向虚线、点线绘制,不局限于水平/垂直线条

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 13:06:23