How to make a surface with a transparent background in pygame

Solution 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.

Solution 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.

Solution 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))