Pygame Image Transparency Confusion

Pygame image transparency confusion

You have to use an image with a transparent background. Be careful and do not download a preview of an image with a checkered background. Just because they are PNGs doesn't mean the background is transparent. The background can still be opaque. Use the following image


If you copy a transparent Surface to another Surface the target Surface has to provide transparency respectively per pixel alpha.

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)

and adapt the method image_at of the class SpriteSheet. Use pygame.SRCALPHA:

class SpriteSheet:
# [...]

def image_at(self, rectangle, colorkey = None):
"""Load a specific image from a specific rectangle."""
# Loads image from x, y, x+offset, y+offset.
rect = pygame.Rect(rectangle)

image = pygame.Surface(rect.size, pygame.SRCALPHA) # <----

image.blit(self.sheet, (0, 0), rect)
if colorkey is not None:
if colorkey == -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, pygame.RLEACCEL)
return image

Or use convert_alpha():

class SpriteSheet:
# [...]

def image_at(self, rectangle, colorkey = None):
"""Load a specific image from a specific rectangle."""
# Loads image from x, y, x+offset, y+offset.
rect = pygame.Rect(rectangle)

image = pygame.Surface(rect.size).convert_alpha() # <----
image.fill((0, 0, 0, 0)) # <---

image.blit(self.sheet, (0, 0), rect)
if colorkey is not None:
if colorkey == -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, pygame.RLEACCEL)
return image

See also:

  • How can I make an Image with a transparent Backround in Pygame?
  • How do I blit a PNG with some transparency onto a surface in Pygame?

Note that chess pieces can also be drawn through a Unicode text.

See Displaying unicode symbols using pygame

Problem with alpha channels in my picture (PyGame)

Ensure that image has a transparency information. If the background isn't transparent, you can't magically get it (except the background has a uniform color). See Pygame image transparency confusion


You have to use convert_alpha instead of convert:

self.spritesheet = pygame.image.load(filename).convert()

self.spritesheet = pygame.image.load(filename).convert_alpha()

Use convert_alpha() to create a copy of the Surface with an image format that provides alpha per pixel. When using convert, the alpha channel and the transparency of the image is lost.

Additionally create a Surface with a per pixel alpha format. Set the SRCALPHA flag to create a surface with an image format that includes a per-pixel alpha:

image = pygame.Surface((width, height))

image = pygame.Surface((width, height), pygame.SRCALPHA)
class Spritesheet:
# utility class for loading and parsing spritesheets
def __init__(self, filename):
self.spritesheet = pygame.image.load(filename).convert_alpha()

def get_image(self, x, y, width, height):
# grab an image out of a larger spritesheet
image = pygame.Surface((width, height), pygame.SRCALPHA)
image.fill(pygame.color.Color("black"))
image.blit(self.spritesheet, (0, 0), (x, y, width, height))
return image

Alternatively you can create a sub-surface with pygame.Surface.subsurface. See How can I crop an image with Pygame?.

class Spritesheet:
# utility class for loading and parsing spritesheets
def __init__(self, filename):
self.spritesheet = pygame.image.load(filename).convert_alpha()

def get_image(self, x, y, width, height):
return image.subsurface(pygame.Rect(x, y, width, height))

Transparency in pygame sprites

If you are copying an image with a per pixel alpha format on another pygame.Surface onto another surface, you need to ensure that the target Surface has a per pixel alpha format, too. If the target cannot save the alpha channel, the transparency will be lost. Set the SRCALPHA flag to create a surface with an image format that includes a per-pixel alpha.

self.image = pygame.Surface([128, 128])

self.image = pygame.Surface([128, 128], pygame.SRCALPHA)

class Piece:

class Piece(pygame.sprite.Sprite):
def __init__(self, kind, posx, posy, sheet, color):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)

# Create an image for the piece and fill it with the image
# TO DO: cut the right type of piece from a sheet, preferably before constructing the object
self.image = pygame.Surface([128, 128], pygame.SRCALPHA)
self.image.blit(sheet, [0, 0])

self.kind = kind # piece type, designated with an uppercase letter, eg. Q for queen
self.color = color # W or B for white or black

# Fetch the rectangle object that has the dimensions of the image
# Update the position of this object by setting the values of rect.x and rect.y
self.rect = self.image.get_rect()
self.rect.x = posx
self.rect.y = posy

Pygame transparency issue

In pygame you must set a background color for antialiased text if you want it to use a color key (which allows you to render transparent text). To get the result you want you just need to match the background color to the surface color, in this case white. The below code (starting right after the for i in ...) worked for me:

surface.fill(WHITE)
textSurfaceObj = fontObj.render(str(i), True, (255, 0, 0),WHITE)
textSurfaceObj.set_alpha(50)
surface.blit(textSurfaceObj,(0,0))
pygame.display.update()
pygame.time.wait(500)

Edit: I did a little digging as to what's going on here, and this mailing list post details the backend properties that cause this for anyone interested.

make a rect transparent in pygame

If you want to make the images transparent, you need to make sure that the alpha channel of the images is set. Additionally you must use convert_alpha() instead of convert():

if ball_color:
ball = pygame.image.load("ball.png").convert_alpha()
else:
ball = pygame.image.load("medicine-ball.png").convert_alpha()

See also the answers to the questions:

  • How to convert the background color of image to match the color of Pygame window?
  • Pygame image transparency confusion
  • pygame image background does not match main background
  • How can I make an Image with a transparent Backround in Pygame?


make a rect transparent in pygame

Unfortunately there is no good way to draw a transparent shape. See the answers to the question Draw a transparent rectangle in pygame and see pygame.draw module:

A color's alpha value will be written directly into the surface [...], but the draw function will not draw transparently.

Hence you need to do a workaround:

  1. Create a pygame.Surface object with a per-pixel alpha format large enough to cover the shape.
  2. Draw the shape on the _Surface.
  3. Blend the Surface with the target Surface. blit() by default blends 2 Surfaces

For example 3 functions, which can draw transparent rectangles, circles and polygons:

def draw_rect_alpha(surface, color, rect):
shape_surf = pygame.Surface(pygame.Rect(rect).size, pygame.SRCALPHA)
pygame.draw.rect(shape_surf, color, shape_surf.get_rect())
surface.blit(shape_surf, rect)

Use the function in your code instead of pygame.draw.rect, alpha is a value in range [0, 255]:

def rect(x1, y1, x2, y2, alpha = 255):
#pygame.draw.rect(screen, (0,0,0), (x1,y1,x2,y2))
draw_rect_alpha(screen, (0, 0, 0, alpha), (x1, y1, x2, y2))


Related Topics



Leave a reply



Submit