Transparency issues drawing a rectangle with rounded corners

不羁岁月 提交于 2019-12-11 02:12:43

问题


I'm attemping to draw rectangles with rounded corners using some code I found in a tutorial, modified slightly by me:

# 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))     

But my results look like this after showing it with tkinter:

Note the grey square corners outside of the rounded corners. This seem to happen on both my Windows and Ubuntu development machines. I'm not sure how they got there or how to get rid of them.


回答1:


Turns out that the paste function needs a mask, even if the original image has an alpha channel itself. So you can use the alpha channel of the image that you're merging as the mask straight up:

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


来源:https://stackoverflow.com/questions/48784578/transparency-issues-drawing-a-rectangle-with-rounded-corners

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!