Pygame Python 字体大小

问题描述

所以今天我发布了一个关于 pygame 的问题,我得到了答案 我必须在 pygame 中使用一个名为 pygame.font.Font.size() 的函数我去了 pygame 的文档并找到了这个函数,但我不明白文档的含义我想我明白我应该将参数作为字符串给出,如果我要将其呈现为文本,它会给出我的字符串的高度和宽度我知道我无法清楚地解释它,但我会努力的。

这里有一些代码来解释它:

import pygame
pygame.init()
width = 800
height = 600
a = [""]
win = pygame.display.set_mode((width,height))
font = pygame.font.Font("freesansbold.ttf",32)
run = True

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

    for i in "hello how are you?":
        a[0] = a[0] + i
        text_1 = font.render(a[0],True,(255,255,255))
        win.fill((0,0))
        win.blit(text_1,(0,0))
        print(font.size(i))
        pygame.display.update()
    a[0] = ''
    run = False
pygame.quit()

如果您无法理解,我很抱歉。我的问题是:如果您运行它,它会运行一秒钟然后消失,但是如果您查看控制台,您会看到一些元组值。根据我的说法,第一个元组的第一个值是,如果我在屏幕上呈现字母 h,则字母的宽度是第一个元组的第一个元素,而 h 的高度是第一个元组的第二个元素。对于第二个,它会是同样的事情,但只是对于第二个元组应用问题“你好,你好吗?”的过程。如果您注意到某些字符的宽度不同。但我的问题是为什么所有元素的高度都相同? 字母h的高度和字母e的高度不一样他们为什么控制台给我同样的高度?

解决方法

Pygame 字体对象是位图字体。每个字形都用位图表示,高度字体在创建 pygame.font.Font 对象时指定。例如32:

font = pygame.font.Font("freesansbold.ttf",32)

字形的宽度不同。 pygame.font.Font.size 返回所有字形的宽度总和。高度始终是字体的高度。但是,字母本身可能只覆盖位图的一部分。

您可以通过获取字形的边界矩形来对此进行调查:

glyph_rect = pygame.mask.from_surface(text_1).get_bounding_rects()[0]

例如:

import pygame
pygame.init()
win = pygame.display.set_mode((800,600))
font = pygame.font.Font("freesansbold.ttf",32)
i = 0
text = "hello how are you?"
run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    letter = text[i]
    text_1 = font.render(letter,True,(255,255,255))
        
    bw,bh = font.size(letter)
    glyph_rect = pygame.mask.from_surface(text_1).get_bounding_rects()
    if glyph_rect:
        gh = glyph_rect[0].height
        print(f'letter {letter}  bitmap height: {bh}  glyph height: {gh}')

    win.fill((0,0))
    win.blit(text_1,(0,0))
    pygame.display.update()

    i += 1
    run = i < len(text)

pygame.quit()

输出:

letter h  bitmap height: 32  glyph height: 23
letter e  bitmap height: 32  glyph height: 17
letter l  bitmap height: 32  glyph height: 23
letter l  bitmap height: 32  glyph height: 23
letter o  bitmap height: 32  glyph height: 17
letter h  bitmap height: 32  glyph height: 23
letter o  bitmap height: 32  glyph height: 17
letter w  bitmap height: 32  glyph height: 17
letter a  bitmap height: 32  glyph height: 17
letter r  bitmap height: 32  glyph height: 17
letter e  bitmap height: 32  glyph height: 17
letter y  bitmap height: 33  glyph height: 24
letter o  bitmap height: 32  glyph height: 17
letter u  bitmap height: 32  glyph height: 17
letter ?  bitmap height: 32  glyph height: 18