微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

您如何确定渲染的文本宽度,使其可以在pygame中居中?

如何解决您如何确定渲染的文本宽度,使其可以在pygame中居中?

我正在创建我的第一个Pygame棋盘游戏。我想在游戏板右侧的侧栏中显示游戏标题。我已经计算了侧边栏的宽度,但是现在我还没有找到一种方法来报告渲染文本的宽度,因此我可以从中心线减去一半的宽度。

是否有此功能?我搜索了其他几个站点,但尚未找到正确的答案。

解决方法

用于在pygame中显示文本:

  • 使用 pygame.font.SysFont 设置字体名称和大小
  • 使用 Sysfont.render 创建文本的表面对象
  • 使用矩形中心设置文本表面的中心
  • 使用 Surface.blit 将文本表面绘制到主屏幕表面上

下面是一些示例代码:

import pygame 
pygame.init()

win = pygame.display.set_mode((300,100))
pygame.display.set_caption("Text")

font = pygame.font.SysFont("impact",40)  # font name and size
text = font.render("<< Python >>",False,(100,255,100)) # surface for text
textRect = text.get_rect()
textRect.center = (300//2,100//2)  # center of text is screen center
win.blit(text,textRect) # draw text
pygame.display.update()

while True:
    pygame.time.delay(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit(); exit()

输出

Text

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。