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.
Asked
Active
Viewed 1.1k times
4
-
Do you want to know how to draw only the outline or how to make the outline transparent? To draw an outline you can just pass an int which determines the width as the fourth argument to [`pygame.draw.rect`](http://www.pygame.org/docs/ref/draw.html#pygame.draw.rect). The problem is that it looks rather ugly for large widths because there will be gaps at the corners. You could also create your own rect outline function and draw four lines. – skrx Nov 11 '18 at 09:38
1 Answers
11
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))

skrx
- 19,980
- 5
- 34
- 48