gpt4 book ai didi

python - 使用 Pygame 显示文本的透明度问题

转载 作者:行者123 更新时间:2023-12-04 03:34:26 38 4
gpt4 key购买 nike

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()

最佳答案

问题在于您放置文本的表面。如果要保持文本形成的透明度,则需要创建一个 pygame.Surface 具有每像素 alpha 格式的对象。使用 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))
enter image description here

关于python - 使用 Pygame 显示文本的透明度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67188510/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com