How to make a surface with a transparent background in pygame

All we need is an easy explanation of the problem, so here it is.

Can someone give me some example code that creates a surface with a transparent background in pygame?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

This should do it:

image = pygame.Surface([640,480], pygame.SRCALPHA, 32)
image = image.convert_alpha()

Make sure that the color depth (32) stays explicitly set else this will not work.

Method 2

You can also give it a colorkey, much like GIF file transparency. This is the most common way to make sprites. The original bitmap has the artwork, and has a certain color as background that will not be drawn, which is the colorkey:

surf.set_colorkey((255,0,255)) // Sets the colorkey to that hideous purple

Surfaces that uses colorkey instead of alpha are a lot faster to blit since they don’t require any blend math. The SDL surface uses a simple bitmask when it has a colorkey set, which blits practically without overhead.

Method 3

You have 3 possibilities:

  • Set a transparent color key with set_colorkey()

    The color key specifies the color that is treated as transparent. For example, if you have an image with a black background that should be transparent, set a black color key:

    my_surface.set_colorkey((0, 0, 0))
    
  • You can enable additional functions when creating a new surface. Set the SRCALPHA flag to create a surface with an image format that includes a per-pixel alpha. The initial value of the pixels is (0, 0, 0, 0):

    my_surface = pygame.Surface((width, height), pygame.SRCALPHA)
    
  • Use convert_alpha() to create a copy of the Surface with an image format that provides alpha per pixel.

    However, if you create a new surface and use convert_alpha(), the alpha channels are initially set to maximum. The initial value of the pixels is (0, 0, 0, 255). You need to fill the entire surface with a transparent color before you can draw anything on it:

    my_surface = pygame.Surface((width, height))
    my_surface = my_surface.convert_alpha()
    my_surface.fill((0, 0, 0, 0))
    

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply