pythonpygamespritepygame-surfacealpha-transparency

How i can remove the black background on my sprite sheet in pygame


I'm trying to learn how use sprite sheets on pygame , and on my first try my sprite for some reason have a black background , i don't know how i can fix this problem , i alredy put 000 on the color key but when i do this the sprite be all buggy

import pygame


class Spritesheet(pygame.sprite.Sprite):
def __init__(self, filename, *groups):
    super().__init__(*groups)
    self.filename = filename
    self.spritesheet = pygame.image.load(filename).convert()

def get_sprite(self, x, y, w, h):
    sprite = pygame.Surface((w, h))
    sprite.set_colorkey(( 0 , 0 , 0))
    sprite.blit(self.spritesheet, (0, 0), (x, y, w, h))
    return sprite

    pass

colorkey 0 0 0

colorkey with any number


Solution

  • Do not set the color key and remove the line:

    sprite.set_colorkey(( 0 , 0 , 0))

    But use convert_alpha() instead of convert()

    self.spritesheet = pygame.image.load(filename).convert()

    self.spritesheet = pygame.image.load(filename).convert_alpha()
    

    The pygame documentation notes that:

    The returned Surface will contain the same color format, colorkey and alpha transparency as the file it came from. You will often want to call convert() with no arguments, to create a copy that will draw more quickly on the screen.
    For alpha transparency, like in .png images, use the convert_alpha() method after loading so that the image has per pixel transparency.

    So if you call convert(), the alpha information per pixel is lost and the image is given an opaque background.


    When you blit the image on a new surface, the target surface must provide a per pixel alpha format. Create a surface with an alpha channel per pixel using the SRCALPHA flag:

    sprite = pygame.Surface((w, h))

    sprite = pygame.Surface((w, h), pygame.SRCALPHA)
    

    Spritesheet class:

    class Spritesheet(pygame.sprite.Sprite):
        def __init__(self, filename, *groups):
            super().__init__(*groups)
            self.filename = filename
            self.spritesheet = pygame.image.load(filename).convert_alpha()
    
        def get_sprite(self, x, y, w, h):
            sprite = pygame.Surface((w, h), pygame.SRCALPHA)
            sprite.blit(self.spritesheet, (0, 0), (x, y, w, h))
            return sprite
    

    Also see: