当鼠标未悬停在游戏中时,我试图使用户界面事物变得透明。但由于某种原因,当我设置图像的 alpha 值使其变得透明时,什么也没有发生。以下是一些可复制问题的可运行代码:
import pygame
WHITE = (255, 255, 255)
class UI:
def __init__(self):
self.img = pygame.image.load("ink_bar_solid.png")
self.img.set_alpha(0)
self.ink_bar_rect = self.img.get_bounding_rect()
self.x, self.y = 0, 10
resolution = (500, 500)
screen = pygame.display.set_mode(resolution)
mouse = pygame.mouse.get_pos
ink_bar = UI()
run = True
def mouse_over():
if ink_bar.ink_bar_rect.collidepoint(mouse()):
ink_bar.img.set_alpha(255)
else:
ink_bar.img.set_alpha(0)
while run:
mouse_over()
screen.fill(WHITE)
screen.blit(ink_bar.img, (ink_bar.x, ink_bar.y))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
break
pygame.display.flip()
pygame.quit()
非常感谢任何帮助! 编辑:我收到某人的评论,他说他们使用了自己的图像并且效果很好...执行程序时我收到此警告:
libpng warning: iCCP: known incorrect sRGB profile
它不能正确传输的原因是因为我的文件吗?
最佳答案
set_alpha
方法似乎不适用于未转换的 png 文件。调用convert
方法还将极大地提高 blit 性能:
self.img = pygame.image.load("ink_bar_solid.png").convert()
它也不适用于每像素 alpha 表面(使用 convert_alpha
转换的表面或使用 pygame.SRCALPHA
标志创建的表面)。可以通过用透明白色填充它们并传递 pygame.BLEND_RGBA_MULT 特殊标志来更改每像素表面的 alpha,例如:
image = pygame.image.load('an_image.png').convert_alpha()
# Make a copy so that the original doesn't get modified.
transparent_image = image.copy()
transparent_image.fill((255, 255, 255, 100), special_flags=pygame.BLEND_RGBA_MULT)
关于python - Pygame 表面的 alpha 不影响透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53137497/