使用
pygame.font模块时,渲染文本时不会考虑文本颜色的Alpha通道,但请参见
pygame.font.Font.render:
抗锯齿图像被渲染为24位RGB图像。如果背景是透明的,则将包含像素alpha。
和
pygame.Surface.set_alpha
在pygame 2.0中进行了更改:可以将每个表面的alpha与每个像素的alpha组合在一起。
因此,用渲染文本后设置透明度就足够了
set_alpha。这甚至适用于抗锯齿的文本:
font = pygame.font.SysFont(None, 150)text_surf = font.render('test text', True, (255, 0, 0))text_surf.set_alpha(127)window.blit(text_surf, (x, y))最小示例:
[ repl.it/@Rabbid76/PyGame-TransparentText](https://repl.it/@Rabbid76/PyGame-TransparentText#main.py)
import pygamepygame.init()window = pygame.display.set_mode((500, 300))clock = pygame.time.Clock()font = pygame.font.SysFont(None, 150)text_surf = font.render('test text', True, (255, 0, 0))text_surf.set_alpha(127)background = pygame.Surface(window.get_size())ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]for rect, color in tiles: pygame.draw.rect(background, color, rect)run = Truewhile run: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False window.blit(background, (0, 0)) window.blit(text_surf, text_surf.get_rect(center = window.get_rect().center)) pygame.display.flip()pygame.quit()exit()通过使用该
pygame.freetype模块,可以在创建文本表面时直接使用透明颜色:
ft_font = pygame.freetype.SysFont('Times New Roman', 150)text_surf2, text_rect2 = ft_font.render('test text', (255, 0, 0, 128))window.blit(text_surf2, (x, y))或者,如果将文本直接渲染到曲面上:
ft_font = pygame.freetype.SysFont('Times New Roman', 150)ft_font.render_to(window, (x, y), 'test text', (255, 0, 0, 128))最小示例:
[ repl.it/@Rabbid76/PyGame-TransparentFreeTypeText](https://repl.it/@Rabbid76/PyGame-TransparentFreeTypeText#main.py)
import pygameimport pygame.freetypepygame.init()window = pygame.display.set_mode((500, 300))clock = pygame.time.Clock()ft_font = pygame.freetype.SysFont('Times New Roman', 150)text_surf2, text_rect2 = ft_font.render('test text', (255, 0, 0, 128))background = pygame.Surface(window.get_size())ts, w, h, c1, c2 = 50, *window.get_size(), (128, 128, 128), (64, 64, 64)tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]for rect, color in tiles: pygame.draw.rect(background, color, rect)run = Truewhile run: clock.tick(60) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False window.blit(background, (0, 0)) text_rect = ft_font.get_rect('test text') text_rect.center = (window.get_width() // 2, window.get_height() // 2 - 70) ft_font.render_to(window, text_rect.topleft, 'test text', (255, 0, 0, 128)) text_rect2.center = (window.get_width() // 2, window.get_height() // 2 + 70) window.blit(text_surf2, text_rect2) pygame.display.flip()pygame.quit()exit()另请参阅文本和字体



