Чтобы центрировать текст в прямоугольнике с помощью Pygame, вы можете использовать следующие методы:
- Метод 1: использование
pygame.font.Fontиpygame.Surface.blit:- Создайте объект
pygame.font.Fontс нужным шрифтом и размером. - Отобразите текст с помощью метода
renderобъекта шрифта, который возвращает объектpygame.Surface. - Получите размеры текстовой поверхности с помощью метода
get_rect. - Вычислите координаты, чтобы центрировать текст внутри прямоугольника.
- Используйте метод
blit, чтобы нарисовать поверхность текста на нужном прямоугольнике.
- Создайте объект
import pygame
pygame.init()
font = pygame.font.Font(None, 32) # Replace None with your desired font file and 32 with the desired font size
text = font.render("Your Text", True, (255, 255, 255)) # Replace "Your Text" with the actual text and (255, 255, 255) with the text color
rect = pygame.Rect(x, y, width, height) # Replace x, y, width, height with the rect dimensions
text_rect = text.get_rect()
text_rect.center = rect.center
pygame.display.set_mode((800, 600)) # Replace (800, 600) with your desired window size
screen = pygame.display.get_surface()
screen.fill((0, 0, 0)) # Replace (0, 0, 0) with the desired background color
screen.blit(text, text_rect)
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
- Метод 2: использование
pygame.font.SysFontиpygame.draw.rect:- Используйте функцию
pygame.font.SysFont, чтобы создать объект шрифта с системным шрифтом и размером. - Вызовите метод
renderобъекта шрифта, чтобы создать текстовую поверхность. - Используйте метод
get_rect, чтобы получить размеры текстовой поверхности. - Создайте прямоугольник с помощью функции
pygame.Rectс нужными размерами. - Используйте атрибут
centerпрямоугольника, чтобы центрировать поверхность текста внутри прямоугольника. - Нарисуйте прямоугольник и скопируйте на него поверхность текста с помощью функций
pygame.draw.rectиblit.
- Используйте функцию
import pygame
pygame.init()
font = pygame.font.SysFont(None, 32) # Replace None with a system font and 32 with the desired font size
text = font.render("Your Text", True, (255, 255, 255)) # Replace "Your Text" with the actual text and (255, 255, 255) with the text color
rect = pygame.Rect(x, y, width, height) # Replace x, y, width, height with the rect dimensions
text_rect = text.get_rect()
text_rect.center = rect.center
pygame.display.set_mode((800, 600)) # Replace (800, 600) with your desired window size
screen = pygame.display.get_surface()
screen.fill((0, 0, 0)) # Replace (0, 0, 0) with the desired background color
pygame.draw.rect(screen, (255, 0, 0), rect) # Replace (255, 0, 0) with the desired rect color
screen.blit(text, text_rect)
pygame.display.flip()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()