Подтвердить что ты не робот

Python library pygame: центрирующий текст

У меня есть код:

# draw text
font = pygame.font.Font(None, 25)
text = font.render("You win!", True, BLACK)
screen.blit(text, [SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2])

Как мне получить методы ширины и высоты текста, например, в java, поэтому я могу выделить текст как:

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

Если это невозможно, что еще? Я нашел этот пример, но я этого не понимал.

4b9b3361

Ответ 1

Вы можете получить размеры отображаемого текстового изображения с помощью text.get_rect(), который возвращает объект Rect с width и height, среди прочих (см. связанную документацию для полного списка). То есть вы можете просто сделать text.get_rect().width.

Ответ 2

Вы всегда можете просто центрировать текстовый прямоугольник, когда вы его захватите:

# 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)

просто еще один вариант

Ответ 3

Представленный текст близок к прозрачной поверхности в Pygame. Таким образом, вы можете использовать описанные здесь методы класса поверхности: http://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_width

Итак, для вас будет работать следующее:

text.get_width()

text.get_height()

Ответ 4

Я использовал эти 2 метода, чтобы написать в центре

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()

Ответ 5

Просто пример:

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) означает количество пикселей вправо и количество пикселей вниз.