Home > Blockchain >  Pygame change image colour but preserve transparency
Pygame change image colour but preserve transparency

Time:03-25

I've got a function that takes an image and adjusts all of the RGB values by a given amount:

def colour(self,img,col):
    img = self.my_image.copy()
    col = (col[0],col[1],col[2],0)
    img.fill(col, None, pygame.BLEND_RGBA_ADD)
    return img

I want to apply this to a partially transparent image. But when I apply this to the image, the transparent pixels become coloured. I want these pixels to stay transparent, but any opaque pixels to be coloured as normal. Is there any way I can do this, without having to loop through every pixel and check if each one is transparent before adjusting it? Thanks

CodePudding user response:

fill treats the color to be solid. You have to use blit. Create a transparent image the size of the source image and fill it with the color. Finally, mix both images:

def colour(self, img, col):
    img = self.my_image.copy()
    color_img = pygame.Surface(img.get_size(), pygame.SRCALPHA)
    color_img.fill((col[0], col[1], col[2], 0))
    img.blit(color_img, (0, 0), special_flags = pygame.BLEND_RGBA_ADD)
    return img

See also Is it possible to change sprite colours in Pygame?

  • Related