PyGame: Applying transparency to an image with alpha?

Synthead picture Synthead · Oct 14, 2012 · Viewed 31.8k times · Source

I want to display an image with alpha with a specified transparency, but can't figure out how to do it.

To elaborate on how I'm struggling with this, the blurb below is a slightly modified hunk of code from this SO answer, but if you run it, you'll see that "image" loses it's native alpha, while the alpha of "image2" never changes! Yuck.

#!/usr/bin/env python

import pygame, sys

pygame.init()

window = pygame.display.set_mode((200, 200))
background = pygame.Surface((window.get_size()))
background.fill((255, 255, 255))
image = image2 = pygame.image.load('alpha.png')

image = image.convert()
rect = image.get_rect()

image2 = image2.convert_alpha()
rect2 = image2.get_rect()

rect2.left = rect.width + 1

i = 0
while True:
  for event in pygame.event.get():
    if event.type == 12:
      pygame.quit()
      sys.exit()

  image.set_alpha(i)
  image2.set_alpha(i)

  window.fill((255, 255, 255))
  window.blit(background, background.get_rect())
  window.blit(image, rect)
  window.blit(image2, rect2)

  if i == 255:
    i = 0
  else:
    i += 1

  pygame.display.update()
  pygame.time.Clock().tick(60)

So ... how is it done?

Answer

DR0ID picture DR0ID · Apr 23, 2013

Make a copy of the image you want to show (to not change the original) and use following:

self.image = self.original_image.copy()
# this works on images with per pixel alpha too
alpha = 128
self.image.fill((255, 255, 255, alpha), None, pygame.BLEND_RGBA_MULT)

Sorry, to not provide a full example.