pygame:居中文本系统字体文本 [英] Pygame: Centering text system font text

查看:81
本文介绍了pygame:居中文本系统字体文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读过有关居中文本的帖子:

  import pygame导入pygame.freetypepygame.init()窗口= pygame.display.set_mode((400,200))def drawTextCentered(表面,文本,text_size,颜色):text_rect = font.get_rect(文本,大小= 50)text_rect.center = surface.get_rect().centerfont.render_to(表面,text_rect,文本,颜色,大小= 50)字体= pygame.freetype.SysFont("comicsansms",0)运行=真运行时:对于pygame.event.get()中的事件:如果event.type == pygame.QUIT:运行=错误window.fill(0)drawTextCentered(窗口,"Hello World",50,(255,0,0))pygame.display.flip()pygame.quit()出口() 

I have read this post about centering text: Pygame - How to Center Text

However instead of importing text from a file:

font = pygame.font.Font("example_font.tff", 25)

I want to use a font from the users system

font = pygame.freetype.SysFont("comicsansms", 0)

using the freetype module as I think it makes rendering to various sizes easier (like when the user resizes the window)
font.render_to(surface, pos, ..., size=int(surface.get_height()/2))

Im not sure how to set a value for pos where the text will be shown in the center of the surface, as I can't .get_rect() or anything to get the dimensions of the text

Possible solutions?
Getting the dimensions of the text
Using System Fonts with pygame.font.Font()

Thanks!

解决方案

Use pygame.freetype.Font.get_rect to get a pygame.Rect object with the size of the text. Note, freetype.Font and freetype.SysFont have the same interface:

text = "Hello World"
text_size = 50

text_rect = font.get_rect(text, size = text_size)
text_rect.center = surface.get_rect().center 

font.render_to(surface, text_rect, text, color, size = text_size)


Minimal examaple:

import pygame
import pygame.freetype

pygame.init()
window = pygame.display.set_mode((400, 200))

def drawTextCentered(surface, text, text_size, color):
    text_rect = font.get_rect(text, size = 50)
    text_rect.center = surface.get_rect().center 
    font.render_to(surface, text_rect, text, color, size = 50)  

font = pygame.freetype.SysFont("comicsansms", 0) 

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.fill(0)
    drawTextCentered(window, "Hello World", 50, (255, 0, 0))  
    pygame.display.flip()

pygame.quit()
exit()

这篇关于pygame:居中文本系统字体文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆