Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make translucent sprites in pygame

I've just started working with pygame and I'm trying to make a semi-transparent sprite, and the sprite's source file is a non-transparent bitmap file loaded from the disk. I don't want to edit the source image if I can help it. I'm sure there's a way to do this with pygame code, but Google is of no help to me.

like image 693
tankadillo Avatar asked Jan 23 '23 08:01

tankadillo


2 Answers

After loading the image, you will need to enable an alpha channel on the Surface. that will look a little like this:

background = pygame.Display.set_mode()
myimage = pygame.image.load("path/to/image.bmp").convert_alpha(background)

This will load the image and immediately convert it to a pixel format suitable for alpha blending onto the display surface. You could use some other surface if you need to blit to some other, off screen buffer in another format.

You can set per-pixel alpha simply enough, say you have a function which takes a 3-tuple for rgb color value and returns some desired 4tuple of rgba color+alpha, you could alter the surface per pixel:

def set_alphas(color):
    if color == (255,255,0): # magenta means clear
        return (0,0,0,0)
    if color == (0,255,255): # cyan means shadow
        return (0,0,0,128)
    r,g,b = color
    return (r,g,b,255) # otherwise use the solid color from the image.

for row in range(myimage.get_height()):
    for col in range(myimage,get_width()):
        myimage.set_at((row, col), set_alphas(myimage.get_at((row, col))[:3]))

There are other, more useful ways to do this, but this gives you the idea, I hope.

like image 157
SingleNegationElimination Avatar answered Jan 25 '23 21:01

SingleNegationElimination


If your image has a solid color background that you want it to became transparent you can set it as color_key value, and pygame will make it transparent when blitting the image.

eg:

color = image.get_at((0,0)) #we get the color of the upper-left corner pixel
image.set_colorkey(color)
like image 33
Lucas S. Avatar answered Jan 25 '23 22:01

Lucas S.