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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With