The*_*bel 4 python fonts pygame width
我正在使用python与pygame并尝试获取文本的宽度.pygame文档说要使用pygame.font.Font.size().但是我不明白该功能应该采取什么.我一直在说错误
TypeError: descriptor 'size' requires a 'pygame.font.Font' object but received a 'str'.
我的代码我用来获得大小和blit看起来像这样
text=self.font.render(str(x[0]), True, black)
size=pygame.font.Font.size(str(x[0]))
Run Code Online (Sandbox Code Playgroud)
要么
size=pygame.font.Font.size(text))
(都给出错误)
然后它是blitted的
screen.blit(text,[100,100])
基本上我正在尝试创建一个可以居中或包装文本的功能,并且需要能够获得宽度.
Pygame文档说 size(text) -> (width, height)
所以,一旦你创建了你的字体对象,你可以用它size(text)来确定一旦呈现它就会在该特定字体中显示多大的文本
在您的情况下,您的字体对象是self.font,所以要确定它将执行此操作的大小:
text_width, text_height = self.font.size("txt") #txt being whatever str you're rendering
Run Code Online (Sandbox Code Playgroud)
然后你可以使用这两个整数来确定在实际渲染之前你需要放置渲染文本
渲染文本只是一个表面.因此,您可以使用:surface.get_width()resp.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)
Run Code Online (Sandbox Code Playgroud)