Pygame 具有 alpha 的表面不透明

Pygame surface with alpha not blitting transparency

我正在尝试在鼠标未悬停在我的游戏中时使用户界面变得透明。但出于某种原因,当我设置图像的 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

是不是因为我的文件导致它不能正常blit?

set_alpha 方法似乎不适用于未转换的 png 文件。调用 convert 方法也将大大提高 blit 性能:

self.img = pygame.image.load("ink_bar_solid.png").convert()

它也不适用于每像素 alpha 表面(使用 convert_alpha 转换或使用 pygame.SRCALPHA 标志创建的表面)。每个像素表面的 alpha 可以通过用透明的白色填充它们并传递 pygame.BLEND_RGBA_MULT 特殊标志来改变,例如:

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)