如何使用Pygame获取文本宽度
我在用Python和pygame做项目,想要获取文本的宽度。pygame的文档里提到要用 pygame.font.Font.size()
这个方法。但是我不太明白这个方法需要什么参数。我总是收到错误提示,内容是 TypeError: descriptor 'size' requires a 'pygame.font.Font' object but received a 'str'.
我用来获取文本大小和显示的代码是这样的:
text=self.font.render(str(x[0]), True, black)
size=pygame.font.Font.size(str(x[0]))
或者是用 size=pygame.font.Font.size(text)
这行代码。
(这两种方式都会报错)
然后我用 screen.blit(text,[100,100])
把文本显示出来。
总的来说,我想创建一个可以居中或换行文本的函数,所以需要知道文本的宽度。
2 个回答
16
渲染的文本其实只是一个表面。所以你可以使用类似于:surface.get_width() 或 surface.get_height() 这样的代码来获取它的宽度和高度。
这里有一个例子,展示了如何把文本放在屏幕正中央;注意:screen_width 和 screen_height 分别是显示器的宽度和高度。我想你应该知道这些值。
my_text = my_font.render("STRING", 1, (0, 0, 0))
text_width = my_text.get_width()
text_height = my_text.get_height()
screen.blit(my_text, (screen_width // 2 - text_width // 2, screen_height // 2 - text_height // 2)
18
Pygame的文档说 size(text) -> (width, height)
这意味着一旦你创建了字体对象,就可以用 size(text)
来确定用这个字体显示的文本会有多大。
在你的例子中,字体对象是 self.font
,所以要确定文本的大小,你可以这样做:
text_width, text_height = self.font.size("txt") #txt being whatever str you're rendering
然后你可以用这两个数字来决定在渲染文本之前,应该把它放在哪里。