如何解决如何在pygame中的矩形中心绘制文本?
所以我只想在矩形的中心写一些字,比如“玩游戏”或类似的东西,但我不确定要做什么。
def drawText(text,x,y,fSize):
screen_text = pygame.font.SysFont("Calibri",fSize,True).render(text,True,(0,0))
rect = screen_text.get_rect()
rect.center = ((screen_side_length // 2) + x),((screen_side_length // 2) + y)
screen.blit(screen_text,rect)
def main_menu():
user_choice = None
while user_choice == None:
screen.fill((255,255,255))
drawText('main menu',20)
x,y = pygame.mouse.get_pos()
button_1 = pygame.Rect(50,100,200,50)
button_2 = pygame.Rect(50,50)
pygame.draw.rect(screen,(255,0),button_1)
pygame.draw.rect(screen,button_2)
click = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
click = True
pygame.display.update()
clock.tick(15)
return user_choice
解决方法
您必须设置文本矩形的中心:
font = pygame.font.SysFont("Calibri",fSize,True)
def drawTextCenter(text,centerx,centery,fSize):
font.render(text,True,(0,0))
rect = screen_text.get_rect(center = (centerx,centery))
screen.blit(screen_text,rect)
将矩形的中心传递给 drawTextCenter
函数:
button_1 = pygame.Rect(50,100,200,50)
drawTextCenter('main menu',button_1.centerx,button_1.centery,20)
不要在每一帧中都创建 pygame.font.Font
对象。在程序开始时创建一次字体。创建字体对象非常耗时,因为必须读取和解释字体文件。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。