Transparency issues drawing a rectangle with rounded corners

ChewToy Source

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
def round_corner(self, radius, fill):
    corner ='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 ='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.



answered 8 months ago ChewToy #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)

comments powered by Disqus