Skip to main content
 首页 » 编程设计

python之绘制带圆角的矩形的透明度问题

2025年01月19日9yxwkf

我正在尝试使用我在教程中找到的一些代码来绘制圆角矩形,这些代码由我稍作修改:

# Rounded rectangle algorithm copied from http://ju.outofmemory.cn/entry/18060 
def round_corner(self, radius, fill): 
    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=(fill)) 
    return corner 
 
def round_rectangle(self, size, radius, fill): 
    width, height = size 
    rectangle = Image.new('RGBA', size, red) 
    corner = self.round_corner(radius, fill) 
    rectangle.paste(corner, (0, 0)) 
    rectangle.paste(corner.rotate(90), (0, height - radius)) # Rotate the corner and paste it 
    rectangle.paste(corner.rotate(180), (width - radius, height - radius)) 
    rectangle.paste(corner.rotate(270), (width - radius, 0)) 
    return rectangle 
 
    # Get rounded box 
    img = self.round_rectangle((200, 200), 30, black) 
    # Join with output image 
    self.image_canvas.paste(img, (500,500))      

但是用 tkinter 显示后我的结果是这样的:

注意圆角外的灰色方角。这似乎发生在我的 Windows 和 Ubuntu 开发机器上。我不确定它们是如何到达那里或如何摆脱它们的。

请您参考如下方法:

事实证明,粘贴函数需要一个 mask ,即使原始图像本身有一个 alpha channel 。因此,您可以直接使用要合并的图像的 Alpha channel 作为 mask :

 self.image_canvas.paste(img, (500,500), img)