使用 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,255))

# red square
surf1 = pygame.Surface((200,200))
surf1.fill((255,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))

enter image description here