使用 pygame SysFont 填充文本

Padding for text using pygame SysFont

我正在尝试使用 pygame 的 SysFont 在屏幕上显示一些文本,但我希望背景矩形比实际文本稍宽。

当我使用以下代码时,背景似乎正好从第一个字母开始的地方开始,到最后一个字母结束的地方结束。

font = pygame.font.SysFont("Helvetica", 30)
img = font.render("ABC", True, "white", "blue1")
img_width = img.get_width()
img_height = img.get_height()
screen.blit(img, (200, 200, img_width, img_height))

有没有办法在背景颜色的文本左右两侧添加一些填充?我认为也许向 img_width 添加一些内容可能会有所帮助,但事实并非如此。

您需要渲染 Surface 上的文本大于文本 _Surface:

  1. 使用透明背景渲染文本
  2. 创建一个比文本 Surface 大的 Surface(参见 pygame.Rect.inflate
  3. 用背景颜色
  4. 填充表面
  5. blit 表面中心的文字

最小示例:

import pygame

pygame.init()
window = pygame.display.set_mode((300, 200))
clock = pygame.time.Clock()

def create_text_box(font, text, text_color, box_color, margin_x, margin_y):
    text_surf = font.render("ABC", True, text_color, "blue1")
    box_surf = pygame.Surface(text_surf.get_rect().inflate(margin_x, margin_y).size)
    box_surf.fill(box_color)
    box_surf.blit(text_surf, text_surf.get_rect(center = box_surf.get_rect().center))
    return box_surf

font = pygame.font.SysFont(None, 100)
text_surf = create_text_box(font, "ABC", "white", "blue1", 10, 0)

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

    window.fill(0)
    window.blit(text_surf, text_surf.get_rect(center = window.get_rect().center))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
exit()

另见