Search code examples
pygametransparentrectoutline

how to draw transparent rect in pygame


Can I draw a rect which is transparent inside, but not the outline? It would be better if I could set the outline's width.

like this


Solution

  • If you just want to draw the outline of a rect, you can pass an integer as the fourth (the width) argument to pygame.draw.rect:

    pygame.draw.rect(screen, (0, 100, 255), (50, 50, 162, 100), 3)  # width = 3
    

    The problem with this approach is that the corners won't look sharp and clean and the outline can't be transparent.


    You could also use the gfxdraw module to draw several outlines with a for loop:

    def draw_rect_outline(surface, rect, color, width=1):
        x, y, w, h = rect
        width = max(width, 1)  # Draw at least one rect.
        width = min(min(width, w//2), h//2)  # Don't overdraw.
    
        # This draws several smaller outlines inside the first outline. Invert
        # the direction if it should grow outwards.
        for i in range(width):
            pygame.gfxdraw.rectangle(screen, (x+i, y+i, w-i*2, h-i*2), color)
    
    draw_rect_outline(screen, (250, 50, 162, 100), (0, 100, 255, 155), 9)
    

    That also allows you to pass a color with an alpha channel to make the outline transparent.


    It would also be possible to create a transparent surface and draw a rect onto it (you can pass a transparent color here as well):

    surf = pygame.Surface((162, 100), pygame.SRCALPHA)
    pygame.draw.rect(surf, (0, 100, 255, 155), (0, 0, 162, 100), 21)
    

    If you want a filled, transparent rectangle, just fill the complete surface:

    surf.fill((0, 100, 255, 155))