Border behaviour when drawing a rectangle in Pygame

Viewed 39

I'm following a Pygame tutorial on YouTube published by Clear Code. So far it's gone well but I've run into an inconsistency between the demo on the video and the behaviour of my code, I'm pretty sure I'm doing exactly what the tutorial instructs, but my results are different.

I'm attempting to draw a border around a rectangle, the rectangle was created from a surface that contains some text as follows.

test_font = pygame.font.Font('font\Pixeltype.ttf',50)
score_surf = test_font.render('My Game', False, 'Black')
score_rect = score_surf.get_rect(center = (400,50))
#Later in the main loop
pygame.draw.rect(screen,'Pink',score_rect)
pygame.draw.rect(screen,'Pink',score_rect, 6)

My understanding is that the first pygame.draw.rect should colour in the area of the score_rect, and the second should create a border that goes slightly outside the area of the score_rect. This should leave a bit of pink visible all the way around the text. In the video I can see this happening, but when I run the code on my system the second pygame.draw.rect that specifies a border width doesn't seem to have any effect.

I've experimented a bit by removing the first pygame.draw.rect, this works mostly as expected I get a pink rectangular border around my text, but this border is strictly insisde the score_rect.

According to the Pygame documentation specifying the width argument should cause the border to go slightly outside the score_rect. However I'm not seeing this behaviour.

Link to Pygame documentation I'm reading https://www.pygame.org/docs/ref/draw.html#pygame.draw.rect

Link to Youtube video I'm following, and location in video https://youtu.be/AY9MnQ4x3zk?t=4879

Edit: Sorry I forgot to note my software versions Pygame: 2.1.2 Python: 3.10.2 OS Windows 10

Any help would be appreciated.

1 Answers

I've come across people asking this exact question on other sites (not in a way that's very searchable, don't worry), so I'm mainly copy pasting my last answer.

In a recent version of pygame, draw.rect was changed to give "actual rectangles." This has an advantage of looking cleaner in many situations, and the algorithm for them is now significantly faster, helping performance.

I actually talked to someone with your exact same issue (like coming from the same tutorial) on discord, and we decided to use a rect.inflate() call to grow the rectangle out before drawing it behind the text.

For example, you could do something like

pygame.draw.rect(screen, 'Pink', score_rect.inflate(10,10)) Instead of both Clear's rect calls.

Or if you want to preserve the slight corner rounding you could do

pygame.draw.rect(screen, 'Pink', score_rect.inflate(10,10), border_radius=3)

So this just uses the return value of a Rect.inflate call instead of the original Rect itself. Inflate takes an x margin and a y margin, and returns a Rect larger/smaller by those amounts, but still centered in the same location.

Related