python - 如何根据显示分辨率缩放pygame中的字体大小?

标签 python fonts pygame

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 的窗口,则必须按 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 的宽度和高度这是由字体呈现的,你必须使用 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()  

关于python - 如何根据显示分辨率缩放pygame中的字体大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56855775/

相关文章:

fonts - 如何在 Visual Studio Code 中启用递归 (OpenType) 字体代码连字?

pdf - 有没有办法在 PDF 文件中使用自定义字体?

pygame - 计时器未正确启动并且在 pygame 中重新启动游戏时未重置

ios - 为 UILabel 外观设置自定义字体会导致 UIDatePicker 错误

python - Ubuntu pygame获取event.key值

python - 对列表中的 numpy 数组进行 += 操作会增加其他列表元素。 Np数组似乎是独立设置的

python - 使用 Queue() 在 python 分布式应用程序中共享文件

python - Django 模型 CharField 空字符串开始保存为 ('',)?

python - 如何按其中一个元素的字母顺序对元组列表进行排序

python - 带有 django 模板变量的 xslt