如何在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])
我该如何获取文本的宽度和高度,这样我就可以像这样居中文本:
screen.blit(text, [SCREEN_WIDTH / 2 - text_w / 2, SCREEN_HEIGHT / 2 - text_h / 2])
如果这样做不行,还有什么其他方法呢?我找到过这个例子,但我没太理解。
6 个回答
在Pygame中,渲染的文本会被绘制在一个透明的表面上。所以你可以使用这里描述的表面类的方法:
http://www.pygame.org/docs/ref/surface.html#pygame.Surface.get_width
所以对你来说,下面的代码可以这样使用:
text.get_width()
text.get_height()
为了简化文本的使用,我写了这个函数(在居中时,x的值并没有用处)
import pygame
pygame.init()
WIDTH = HEIGHT = 500
screen = pygame.display.set_mode((WIDTH, HEIGHT))
font = pygame.font.SysFont("Arial", 14)
def write(text, x, y, color="Coral",):
text = font.render(text, 1, pygame.Color(color))
text_rect = text.get_rect(center=(WIDTH//2, y))
return text, text_rect
text, text_rect = write("Hello", 10, 10) # this will be centered anyhow, but at 10 height
loop = 1
while loop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
loop = 0
screen.blit(text, text_rect)
pygame.display.update()
pygame.quit()
pygame.Surface.get_rect.get_rect()
这个方法会返回一个矩形,它的大小和Surface对象一样,位置总是从(0, 0)开始,因为Surface对象本身没有位置。你可以通过关键字参数来指定这个矩形的位置。例如,可以用关键字参数center
来设置矩形的中心位置。这些关键字参数会在返回之前应用到pygame.Rect
的属性上(想了解所有的关键字参数,可以查看pygame.Rect
)。
获取文本的矩形,并把文本矩形的中心放在窗口矩形的中心:
text_rect = text.get_rect(center = (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
你甚至可以从显示的Surface中获取窗口的中心:
text_rect = text.get_rect(center = screen.get_rect().center)
或者使用pygame.display.get_surface()
来获取:
text_rect = text.get_rect(center = pygame.display.get_surface().get_rect().center)
你可以用blit
方法把一个Surface画到另一个Surface上。第二个参数可以是一个元组(x, y),表示左上角的位置,或者是一个矩形。如果是矩形的话,只会考虑矩形的左上角。因此,你可以直接把文本矩形传给blit
:
screen.blit(text, text_rect)
最简单的例子:
import pygame
import pygame.font
pygame.init()
font = pygame.font.SysFont(None, 50)
text = font.render('Hello World', True, (255, 0, 0))
window = pygame.display.set_mode((300, 100))
clock = pygame.time.Clock()
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.fill(0)
window.blit(text, text.get_rect(center = window.get_rect().center))
pygame.display.flip()
pygame.quit()
exit()
你可以在抓取文本的矩形时,直接把它居中:
# draw text
font = pygame.font.Font(None, 25)
text = font.render("You win!", True, BLACK)
text_rect = text.get_rect(center=(SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
screen.blit(text, text_rect)
这只是另外一个选择
你可以通过 text.get_rect()
来获取渲染后文本图像的尺寸。这个方法会返回一个 Rect 对象,这个对象里面有很多属性,其中包括 width
(宽度)和 height
(高度)。简单来说,你只需要用 text.get_rect().width
就能得到文本的宽度。