Python library pygame: centering text

I have a 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 text width and height methods, for example, in java, so I can select the text as:

 screen.blit(text, [SCREEN_WIDTH / 2 - text_w / 2, SCREEN_HEIGHT / 2 - text_h / 2]) 

If this is not possible, what else? I found this example, but I did not understand it.

+11
source share
5 answers

You can get the dimensions of the displayed text image using text.get_rect() , which returns a Rect object with width and height , among others (see the related documentation for a complete list). That is, you can just do text.get_rect().width .

+11
source

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

+14
source

The text presented is close to a transparent surface in Pygame. So you can use the surface class methods described here: http://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_width

So, the following will work for you:

text.get_width ()

text.get_height ()

0
source

I used these 2 methods to write in the center

 import pygame from pygame.locals import * pygame.init() pygame.font.init() SURF = pygame.display.set_mode((600, 400)) # font object.................................. def create_font(t,s=72,c=(255,255,0), b=False,i=False): font = pygame.font.SysFont("Arial", s, bold=b, italic=i) text = font.render(t, True, c) textRect = text.get_rect() return [text,textRect] # Text to be rendered with create_font game_over, gobox = create_font("GAME OVER") restart, rbox = create_font("Press Space to restart", 36, (9,0,180)) centerx, centery = SURF.get_width() // 2, SURF.get_height() // 2 gobox = game_over.get_rect(center=(centerx, centery)) rbox.center = int((SURF.get_width() - restart.get_width())//2), restart.get_height() loop = True clock = pygame.time.Clock() while loop == True: SURF.fill((0,0,0)) x, y = pygame.mouse.get_pos() SURF.blit(game_over, gobox) SURF.blit(restart, rbox.center) for e in pygame.event.get(): if e.type == QUIT: loop = 0 pygame.display.update() clock.tick(60) pygame.quit() 
0
source

Just an example:

 import pygame import time pygame.init() screen = pygame.display.set_mode([1920, 1080]) black = pygame.Color(0, 0, 0) white = pygame.Color(255,255,255) def showload(): myFont = pygame.font.SysFont('monaco', 72) Ssurf = myFont.render('loading...', True, black) Srect = Ssurf.get_rect() Srect.midtop = (960, 540) screen.blit(Ssurf, Srect) pygame.display.flip() screen.fill(white) showload() time.sleep(5)` 

Srect.midtop = (960, 540) means the number of pixels to the right and the number of pixels down.

-1
source

Source: https://habr.com/ru/post/970151/


All Articles