Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Center Text in Pygame

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.

like image 808
Xerath Avatar asked Jun 01 '14 18:06

Xerath


People also ask

How do you Blit text in Pygame?

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.

Which function in pygame is used to set the text position on the screen?

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.

What is Blit pygame?

It is a thin wrapper around a Pygame surface that allows you to easily draw images to the screen (“blit” them).


1 Answers

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

like image 142
The4thIceman Avatar answered Sep 26 '22 02:09

The4thIceman