Python Pygame Trasparency showing as black

Viewed 174

I am trying to blit an image with transparencies on top of a Surface with the rest of the map. ( This is the second layer. ) When I blit it, it shows with the transparency as black. Is there a way to fix this. I included the code related to it.

lily_tex = spritesheet.get_sprite(1, 4).convert_alpha()

This gets the image from the spritesheet.

    img = pygame.Surface((self.tilesize, self.tilesize))
    img.blit(self.img, (0, 0), (x, y, self.tilesize, self.tilesize))
    return img.convert()

And this is what pulls it from the sprite sheet. Below is what blits it to a surface to be blitted to the screen buffer.

def create_map(self):
    for map_data in self.map_data:
        for row in range(len(map_data)):
            for column in range(len(map_data[row])):
                if map_data[row][column] == 0:
                    continue
                texture = self.key.get(map_data[row][column])
                self.map_img.blit(texture, (column * self.tilesize, row * self.tilesize))

Thank you

1 Answers

When you call convert() the pixel format of the image is changed. If the image format has per alpha pixel, this information will be lost.

Use convert_alpha() instead of convert():

return img.convert()

return img.convert_alpha()

If the image has no per pixel alpha format you must set the transparent color key with set_colorkey():

img = pygame.Surface((self.tilesize, self.tilesize))
img.blit(self.img, (0, 0), (x, y, self.tilesize, self.tilesize))
img.set_colorkey((0, 0, 0))

Alternatively you can create a surface with per pixel alpha format with the SRCALPHA flag:

img = pygame.Surface((self.tilesize, self.tilesize), pygame.SRCALPHA)
img.blit(self.img, (0, 0), (x, y, self.tilesize, self.tilesize))
Related