首页 > 解决方案 > pygame返回转换后的表面,set_alpha不起作用

问题描述

我有这个功能:

def imgload(dir, file, convert=2, colorkey=None):
    img = pygame.image.load(os.path.join(dir, file))
    if convert == 1:
        img.convert()
    elif convert == 2:
        img.convert_alpha()
    
    if colorkey is not None:
        img.set_colorkey(colorkey)
    return img

然后我有

logo = imgload("Big_Images", "logo.png", 1, (0, 0, 0))

和一个类(不要看缩进,我做错了;在实际代码中是正确的)

class Intro(pygame.sprite.Sprite):
def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    self.image = logo
    self.rect = self.image.get_rect()
    self.rect.centerx = round(WINDOW_WIDTH / 2)
    self.rect.centery = round(WINDOW_HEIGHT / 2)
    self.transparency = 255

def update(self):
    global game_state
    if self.transparency > 0:
        self.transparency -= 1
        self.image.set_alpha(self.transparency)
    else:
        game_state = "home"

游戏循环中的绘制函数(while): if game_state == "intro": WIN.fill(GRAY) all_intro_sprites.draw(WIN) all_intro_sprites.update()

奇怪的是当我这样做时代码工作正常logo= pygame.image.load(os.path.join("Big_Images", "logo.png").convert() 这是图像

标签: pythonpygamesurfacepygame-surface

解决方案


convert()并且convert_alpha()不要将图像转换到位。这些函数创建并返回具有所需像素格式的表面的新副本。您必须将返回值分配给img. 例如:

img = img.convert_alpha() 

更正功能imgload

def imgload(dir, file, convert=2, colorkey=None):
    img = pygame.image.load(os.path.join(dir, file))
    
    if convert == 1:
        img = img.convert()
    elif convert == 2:
        img = img.convert_alpha()
    
    if colorkey is not None:
        img.set_colorkey(colorkey)
    return img

推荐阅读