Pygame 显示文本的透明度问题

Transparency problem displaying text with Pygame

enter image description here我想在根据文本长度调整大小的表面上显示透明文本。 问题是即使在“render”命令中将“None”指定为背景,文本的背景也是黑色的。 我尝试应用针对与我的问题类似的问题给出的解决方案,但它们没有用。 我附上代码并感谢您的任何建议。

import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((800, 600))
screen.fill ((0,0,255))

# red square
surf1 = pygame.Surface((200, 200))
surf1.fill((255, 0, 0))
rect1 = surf1.get_rect()
rect1.topleft = (50, 50)
screen.blit(surf1, rect1)

# Play button
fnt = pygame.font.SysFont("Times New Roman", 27, bold=True)
btn_play = fnt.render("Play", True, (51, 26, 0), None)
btn_play_size = btn_play.get_size()
btn_play_surface = pygame.Surface(btn_play_size)
btn_play_surface.blit(btn_play, (0, 0))
rect_btn_play = pygame.Rect(380, 50, btn_play_size[0], btn_play_size[1])
screen.blit(btn_play_surface, (380, 50))
pygame.display.flip()

def events():
    done = False
    while not done:
        for ev in pygame.event.get():
            if ev.type == QUIT:
                return "quit"
            elif ev.type == MOUSEBUTTONDOWN:
                click = ev.pos
                if rect1.collidepoint(click):
                    return "Red squre"
                elif rect_btn_play.collidepoint(click):
                    return "Play"
                else:
                    print ("You clicked outside of the surfaces")

while True:
    event = events()
    print (event)
    if event == "quit":
        break
pygame.quit()

问题出在放置文本的表面上。如果要保持文本格式的透明度,则需要创建一个具有每像素 alpha 格式的 pygame.Surface 对象。使用 pygame.SRCALPHA 标志:

btn_play_surface = pygame.Surface(btn_play_size)

btn_play_surface = pygame.Surface(btn_play_size, pygame.SRCALPHA)

或者您可以使用 set_colorkey:

设置透明颜色的颜色键
btn_play_surface = pygame.Surface(btn_play_size)
btn_play_surface.set_colorkey((0, 0, 0))