Pygame - 如何居中文本 [英] Pygame - How to Center Text

查看:104
本文介绍了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])

如何获取文本的宽度和高度,以便像这样将文本居中:

How can I get the text's width and height, so I can center text like this:

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

如果这是不可能的,另一种方法是什么?我找到了 this 示例,但我并没有真正理解它.

If this is not possible, what is another way ? I've found this example, but I didn't really understand it.

推荐答案

您可以使用 text.get_rect() 获取渲染文本图像的尺寸,它返回一个 Rect 对象,具有 widthheight 属性,其中其他(有关完整列表,请参阅链接文档).IE.你可以简单地做 text.get_rect().width.

You can get the dimensions of the rendered text image using text.get_rect(), which returns a Rect object with width and height attributes, among others (see the linked documentation for a full list). I.e. you can simply do text.get_rect().width.

这篇关于Pygame - 如何居中文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆