Python图像库(PIL)绘图--带渐变的圆角矩形

9 投票
5 回答
19867 浏览
提问于 2025-04-17 04:27

我正在尝试使用PIL库来绘制一个有圆角的矩形,并且希望这个矩形的颜色有渐变效果。我找到一个很酷的网站(http://web.archive.org/web/20130306020911/http://nadiana.com/pil-tutorial-basic-advanced-drawing#Drawing_Rounded_Corners_Rectangle),上面展示了如何绘制一个单色的圆角矩形,我对此很满意,但我想要的是一个从顶部的浅红色渐变到底部的深红色的矩形。

我最开始的想法是用上面网站的代码先画一个圆角矩形,然后再在这个矩形上覆盖一个从白色到黑色的矩形,使用透明度混合的方式。但我尝试的所有方法都没有成功,反而让我很沮丧。

我看到一些使用numpy的解决方案,但我没有足够的技能把那些代码片段组合成一个成功的解决方案。如果有人能教我如何修改上面链接中的代码,或者实现我的覆盖想法,或者给出一个更好的方法来在Python中绘制带渐变填充的圆角矩形,我将非常感激。

谢谢,
Ferris

5 个回答

7

在Pillow 8.2.0版本中,官方现在提供了圆角矩形的功能,使用的命令是rounded_rectangle。你可以在这里查看详细信息:https://github.com/python-pillow/Pillow/pull/5208

from PIL import Image, ImageDraw
result = Image.new('RGBA', (100, 100))
draw = ImageDraw.Draw(result)
draw.rounded_rectangle(((0, 0), (100, 100)), 20, fill="blue")
result.show()

带圆角的蓝色矩形

如果你需要更平滑的效果,可以看看这个链接:https://github.com/python-pillow/Pillow/issues/4765

11

如果将来有人在寻找一个更简单直接的解决方案,可以直接应用到ImageDraw上,我写了以下内容。

希望这能帮到你。

示例: 这里输入图片描述 代码:

from PIL.ImageDraw import ImageDraw


def rounded_rectangle(self: ImageDraw, xy, corner_radius, fill=None, outline=None):
    upper_left_point = xy[0]
    bottom_right_point = xy[1]
    self.rectangle(
        [
            (upper_left_point[0], upper_left_point[1] + corner_radius),
            (bottom_right_point[0], bottom_right_point[1] - corner_radius)
        ],
        fill=fill,
        outline=outline
    )
    self.rectangle(
        [
            (upper_left_point[0] + corner_radius, upper_left_point[1]),
            (bottom_right_point[0] - corner_radius, bottom_right_point[1])
        ],
        fill=fill,
        outline=outline
    )
    self.pieslice([upper_left_point, (upper_left_point[0] + corner_radius * 2, upper_left_point[1] + corner_radius * 2)],
        180,
        270,
        fill=fill,
        outline=outline
    )
    self.pieslice([(bottom_right_point[0] - corner_radius * 2, bottom_right_point[1] - corner_radius * 2), bottom_right_point],
        0,
        90,
        fill=fill,
        outline=outline
    )
    self.pieslice([(upper_left_point[0], bottom_right_point[1] - corner_radius * 2), (upper_left_point[0] + corner_radius * 2, bottom_right_point[1])],
        90,
        180,
        fill=fill,
        outline=outline
    )
    self.pieslice([(bottom_right_point[0] - corner_radius * 2, upper_left_point[1]), (bottom_right_point[0], upper_left_point[1] + corner_radius * 2)],
        270,
        360,
        fill=fill,
        outline=outline
    )


ImageDraw.rounded_rectangle = rounded_rectangle
14

这是一种非常简单粗暴的方法,但它能完成任务。生成渐变的代码是从这里借来的。

from PIL import Image, ImageDraw

def channel(i, c, size, startFill, stopFill):
    """calculate the value of a single color channel for a single pixel"""
    return startFill[c] + int((i * 1.0 / size) * (stopFill[c] - startFill[c]))

def color(i, size, startFill, stopFill):
    """calculate the RGB value of a single pixel"""
    return tuple([channel(i, c, size, startFill, stopFill) for c in range(3)])

def round_corner(radius):
    """Draw a round corner"""
    corner = Image.new('RGBA', (radius, radius), (0, 0, 0, 0))
    draw = ImageDraw.Draw(corner)
    draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill="blue")
    return corner

def apply_grad_to_corner(corner, gradient, backwards = False, topBottom = False):
    width, height = corner.size
    widthIter = range(width)

    if backwards:
        widthIter.reverse()

    for i in xrange(height):
        gradPos = 0
    for j in widthIter:
                if topBottom:
                    pos = (i,j)
                else:
                    pos = (j,i)
        pix = corner.getpixel(pos)
            gradPos+=1
        if pix[3] != 0:
            corner.putpixel(pos,gradient[gradPos])

    return corner

def round_rectangle(size, radius, startFill, stopFill, runTopBottom = False):
    """Draw a rounded rectangle"""
    width, height = size
    rectangle = Image.new('RGBA', size)

    if runTopBottom:
      si = height
    else:
      si = width

    gradient = [ color(i, width, startFill, stopFill) for i in xrange(si) ]

    if runTopBottom:
        modGrad = []
        for i in xrange(height):
           modGrad += [gradient[i]] * width
        rectangle.putdata(modGrad)
    else:
        rectangle.putdata(gradient*height)

    origCorner = round_corner(radius)

    # upper left
    corner = origCorner
    apply_grad_to_corner(corner,gradient,False,runTopBottom)
    rectangle.paste(corner, (0, 0))

    # lower left
    if runTopBottom: 
        gradient.reverse()
        backwards = True
    else:
        backwards = False


    corner = origCorner.rotate(90)
    apply_grad_to_corner(corner,gradient,backwards,runTopBottom)
    rectangle.paste(corner, (0, height - radius))

    # lower right
    if not runTopBottom: 
        gradient.reverse()

    corner = origCorner.rotate(180)
    apply_grad_to_corner(corner,gradient,True,runTopBottom)
    rectangle.paste(corner, (width - radius, height - radius))

    # upper right
    if runTopBottom: 
        gradient.reverse()
        backwards = False
    else:
        backwards = True

    corner = origCorner.rotate(270)
    apply_grad_to_corner(corner,gradient,backwards,runTopBottom)
    rectangle.paste(corner, (width - radius, 0))

    return rectangle

img = round_rectangle((200, 200), 70, (255,0,0), (0,255,0), True)
img.save("test.png", 'PNG')

从左到右运行(runTopBottom = False):

在这里输入图片描述

从上到下运行(runTopBottom = True):

在这里输入图片描述

撰写回答