如果我在 Pygame 中有两个表面,一个是窗口,另一个包含一些文本,我如何以编程方式将文本表面集中在窗口内(而不是手动使用幻数)?
问问题
611 次
2 回答
1
您可以使用pygame.Rect()和rect.center
,rect.topleft
screen_rect = screen.get_rect() # get screen rectangle
text_rect = text.get_rect() # get text rectangle
text_rect.center = screen_rect.center # center text on screen
现在您可以在屏幕上将文本定位到适当的位置text_rect.topleft
screen.blit( text, text_rect.topleft )
rect
还有其他有用的属性:
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w,h
完整代码:(按空格暂停)
import sys
import pygame
from pygame.locals import *
#----------------------------------------------------------------------
class Game():
def __init__(self):
pygame.init()
fpsClock = pygame.time.Clock()
screen = pygame.display.set_mode((1200,600),0,32)
font = pygame.font.SysFont("", 72)
text_pause = font.render("PAUSE", True, (255, 0, 0))
screen_rect = screen.get_rect() # get screen rect
text_rect = text_pause.get_rect() # get text rect
text_rect.center = screen_rect.center # center text on screen
RUNNING = True
PAUSED = True
while RUNNING:
for event in pygame.event.get():
if event.type==QUIT:
RUNNING = False
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
RUNNING = False
elif event.key == K_SPACE:
PAUSED = not PAUSED
screen.fill(0)
if PAUSED:
screen.blit(text_pause, text_rect.topleft)
pygame.display.update()
fpsClock.tick(25)
# --- finish ---
pygame.quit()
sys.exit()
#----------------------------------------------------------------------
Game().run()
您可以使用rect.center
在鼠标位置居中文本。
完整代码:(移动鼠标)
import sys
import pygame
from pygame.locals import *
#----------------------------------------------------------------------
class Game():
def __init__(self):
pygame.init()
fpsClock = pygame.time.Clock()
screen = pygame.display.set_mode((1200,600),0,32)
font = pygame.font.SysFont("", 72)
text_pause = font.render("PAUSE", True, (255, 0, 0))
screen_rect = screen.get_rect() # get screen rect
text_rect = text_pause.get_rect() # get text rect
text_rect.center = screen_rect.center # center text on screen
# --- mainloop ---
RUNNING = True
PAUSED = True
while RUNNING:
# --- events ---
for event in pygame.event.get():
if event.type==QUIT:
RUNNING = False
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
RUNNING = False
elif event.key == K_SPACE:
PAUSED = not PAUSED
if event.type == MOUSEMOTION:
text_rect.center = event.pos
# --- calcuations/moves ---
# --- draws ---
screen.fill(0)
if PAUSED:
screen.blit(text_pause, text_rect.topleft)
pygame.display.update()
# --- FPS ---
fpsClock.tick(25)
# --- finish ---
pygame.quit()
sys.exit()
#----------------------------------------------------------------------
Game().run()
于 2013-11-05T21:25:08.367 回答
1
你总是可以用数学而不是幻数来做,甚至不知道任何关于pygame
:
top = outer.get_height()/2 - inner.get_height()/2
left = outer.get_width()/2 - inner.get_width()/2
这为您提供了内表面的左上角,在外表面的坐标系中,在任何图形库中(表面坐标系可以具有不同分辨率的库除外)。
于 2013-11-05T21:02:28.707 回答