pythonpygamesurfacepygame-surface

pygame return converted surface with set_alpha not working


I have this function:

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

then I have

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

and a class (don't look at the indentation, I couldn't get it right; it is correct in the actual code)

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"

Draw function in the game loop (while): if game_state == "intro": WIN.fill(GRAY) all_intro_sprites.draw(WIN) all_intro_sprites.update()

The weird thing is that the code works fine when I do logo= pygame.image.load(os.path.join("Big_Images", "logo.png").convert() this is the image


Solution

  • convert() and convert_alpha() do not convert the image in place. The functions create and return a new copy of the surface with the desired pixel format. You have to assigne the return value to img. For instance:

    img = img.convert_alpha() 
    

    Correct the function 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