如何根据显示分辨率缩放 pygame 中的字体大小?
How to scale the font size in pygame based on display resolution?
largeText = pygame.font.Font('digifaw.ttf',450)
字体大小为450,适合全屏显示分辨率1366x768
的文字显示。如何更改字体大小以使其与其他显示分辨率兼容?我查找了 font 的 pydocs,但找不到任何与自动缩放相关的内容。
更新:这是代码片段
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('digifaw.ttf',450)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(1)
您必须手动缩放字体。如果字体适合高度为 768 的 window,则您必须将字体缩放 current_height/768
。例如:
h = screen.get_height();
largeText = pygame.font.Font('digifaw.ttf', int(450*h/768))
注意,您可以使用 pygame.freetype
模块:
import pygame.freetype
font = pygame.freetype.Font('digifaw.ttf')
和方法 .render_to()
,将字体直接渲染到表面:
h = screen.get_height()
font.render_to(screen, (x, y), 'text', color, size=int(450*h/768))
如果要缩放 pygame.Surface
which is rendered by the font, the you've to use pygame.transform.smoothscale()
的宽度和高度:
gameDisplay = pygame.display.set_mode(size, pygame.RESIZABLE)
ref_w, ref_h = gameDisplay.get_size()
def text_objects(text, font):
textSurface = font.render(text, True, black).convert_alpha()
cur_w, cur_h = gameDisplay.get_size()
txt_w, txt_h = textSurface.get_size()
textSurface = pygame.transform.smoothscale(
textSurface, (txt_w * cur_w // ref_w, txt_h * cur_h // ref_h))
return textSurface, textSurface.get_rect()
largeText = pygame.font.Font('digifaw.ttf',450)
字体大小为450,适合全屏显示分辨率1366x768
的文字显示。如何更改字体大小以使其与其他显示分辨率兼容?我查找了 font 的 pydocs,但找不到任何与自动缩放相关的内容。
更新:这是代码片段
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('digifaw.ttf',450)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(1)
您必须手动缩放字体。如果字体适合高度为 768 的 window,则您必须将字体缩放 current_height/768
。例如:
h = screen.get_height();
largeText = pygame.font.Font('digifaw.ttf', int(450*h/768))
注意,您可以使用 pygame.freetype
模块:
import pygame.freetype
font = pygame.freetype.Font('digifaw.ttf')
和方法 .render_to()
,将字体直接渲染到表面:
h = screen.get_height()
font.render_to(screen, (x, y), 'text', color, size=int(450*h/768))
如果要缩放 pygame.Surface
which is rendered by the font, the you've to use pygame.transform.smoothscale()
的宽度和高度:
gameDisplay = pygame.display.set_mode(size, pygame.RESIZABLE)
ref_w, ref_h = gameDisplay.get_size()
def text_objects(text, font):
textSurface = font.render(text, True, black).convert_alpha()
cur_w, cur_h = gameDisplay.get_size()
txt_w, txt_h = textSurface.get_size()
textSurface = pygame.transform.smoothscale(
textSurface, (txt_w * cur_w // ref_w, txt_h * cur_h // ref_h))
return textSurface, textSurface.get_rect()