53

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

Paul D. Eden
  • 19,939
  • 18
  • 59
  • 63

3 Answers3

60

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.

Community
  • 1
  • 1
UnkwnTech
  • 88,102
  • 65
  • 184
  • 229
  • 6
    I second that - `image = pygame.Surface([640, 480], pygame.SRCALPHA)` is all you need. – Jayce May 20 '19 at 18:01
  • I would like to also add that you now set colors like this: `cloud_color = (255, 255, 255, 120)` where the last value can range from 0 to 255. – Ethan McRae Aug 07 '21 at 16:39
23

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.

Zoomulator
  • 20,774
  • 7
  • 28
  • 32
7

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))
    
Rabbid76
  • 202,892
  • 27
  • 131
  • 174