【问题标题】:How do you center text being displayed with pygame? [duplicate]pygame 中显示的文本如何居中? [复制]
【发布时间】:2021-03-31 19:23:36
【问题描述】:

我有这段代码,它没有在屏幕宽度的中间显示分配给变量“title”的文本。 除了根据文本的长度猜测位置之外,还有什么方法可以将其居中?

import pygame
pygame.init()
pygame.font.init()

WIDTH = 1920
HEIGHT = 1080

CYAN = (0, 255, 255)
RED = (255, 0, 0)

window = pygame.display.set_mode((WIDTH, HEIGHT))

def startWindow(): 
    titleFont = pygame.font.SysFont("Comic Sans MS", 35)

    window.fill(RED)
    title = titleFont.render("Ball Game", False, CYAN)
    window.blit(title, (WIDTH//2, 35))
    pygame.display.update()


startWindow()

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    您应该在渲染后首先获取文本矩形,然后将矩形相对于屏幕宽度居中。之后,您可以将其传递给 blit。

    centerTitle = title.get_rect(center=(WIDTH/2,35))
    window.blit(title, centerTitle)
    

    【讨论】:

    • 谢谢,效果很好 我有这个问题有一段时间了。
    猜你喜欢
    • 2014-01-17
    • 2021-09-22
    • 2014-07-21
    • 2023-01-09
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多