3

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

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
Some Goose
  • 43
  • 3
  • 1
    Not certain, but I will suggest that the `return img.convert()` might need to be `return img.convert_alpha()`. However if you have already `convert()`ed the `self.img` you should not need to convert the image/surface resulting from the blit. Doing the `convert()`again is likely removing the alpha that was preserved in the original `convert_alpha()` – Glenn Mackintosh Aug 06 '20 at 18:29
  • Can you try: `img = pygame.Surface((self.tilesize, self.tilesize), pygame.SRCALPHA)`. This creates the surface with an alpha-channel. – Kingsley Aug 07 '20 at 04:14
  • Thank you, after looking at this I added the `convert_alpha()` and saw somewhere else to add `img.setcolorkey((0, 0, 0))` as that was the color of the image background. I think it needed that as the Image might have used black to show transparency. While looking at the image in file explorer, it sometimes would be black. The surface with the alpha channel may have worked, but I think it was the image, not pygame. – Some Goose Aug 07 '20 at 12:14

1 Answers1

0

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))
Rabbid76
  • 202,892
  • 27
  • 131
  • 174