【问题标题】:how to center text in a rectangle in pygame [duplicate]如何在pygame的矩形中居中文本[重复]
【发布时间】:2021-09-22 06:32:15
【问题描述】:

我在 pygame 中制作游戏,但我不知道如何在矩形中居中放置一些文本。我使用 pygame.draw_rect(win, color, (x, y, w, h)) 和文本绘制矩形 text = font.render("text", 1, color). 我知道我可以使用 text_rect = text.get_Rect() 来获取文本的 rect 对象。但我不知道如何使用它们来使文本居中。我在网上找了一个解决办法,没找到

【问题讨论】:

  • 获取两个矩形的中心点,计算差值,然后将文本blit到应该blit的地方

标签: python python-3.x pygame


【解决方案1】:

您可以从通过渲染字体生成的表面获得一个矩形。然后将矩形的中心设置为矩形的中心。然后blit你的字体表面到主表面。

这是一个使用鼠标滚轮放大和缩小边框矩形以显示字体保持居中的小示例。按一个键随机化文本。

import random
import pygame
WIDTH, HEIGHT = 320, 240
pygame.init()
pygame.font.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# use the first available font
font = pygame.font.SysFont(pygame.font.get_fonts()[0], 60)
pygame.display.set_caption("Centering Font Rect")

text = "Initial Text"
widget = font.render(text, True, pygame.Color("seagreen"))
border = pygame.Rect(10, 10, WIDTH - 40, HEIGHT - 40)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            # change the text
            text = random.choice(["Short", "Long Looooong", ".", "+++", "ABC"])
            widget = font.render(text, True, pygame.Color("purple"))
        elif event.type == pygame.MOUSEWHEEL:
            # enlarge or shrink the border rect
            border.inflate_ip(event.y, event.y)
    screen.fill(pygame.Color("turquoise"))
    # draw border rect
    pygame.draw.rect(screen, pygame.Color("red"), border, width=1)
    # get the current font rect
    font_rect = widget.get_rect()
    # move rect to be centered on border rect
    font_rect.center = border.center
    screen.blit(widget, font_rect)
    # update display
    pygame.display.update()
pygame.quit()

这表明:

然后在调整大小后:

【讨论】:

    猜你喜欢
    • 2023-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 2014-07-21
    • 2021-03-31
    相关资源
    最近更新 更多