I have some code:
# draw text font = pygame.font.Font(None, 25) text = font.render("You win!", True, BLACK) screen.blit(text, [SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2])
How can I get the text's width and height, so I can center text like this:
screen.blit(text, [SCREEN_WIDTH / 2 - text_w / 2, SCREEN_HEIGHT / 2 - text_h / 2])
If this is not possible, what is another way ? I've found this example, but I didn't really understand it.
Pygame does not provide a direct way to write text onto a Surface object. The method render() must be used to create a Surface object from the text, which then can be blit to the screen. The method render() can only render single lines. A newline character is not rendered.
Create a rectangular object for the text surface object using get_rect() method of pygame text surface object. Set the position of the Rectangular object by setting the value of the center property of pygame rectangular object.
It is a thin wrapper around a Pygame surface that allows you to easily draw images to the screen (“blit” them).
You can always just center the text rectangle when you grab it:
# draw text font = pygame.font.Font(None, 25) text = font.render("You win!", True, BLACK) text_rect = text.get_rect(center=(SCREEN_WIDTH/2, SCREEN_HEIGHT/2)) screen.blit(text, text_rect)
just another option
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With