Python – Stack different types of transparency in pygame

Stack different types of transparency in pygame… here is a solution to the problem.

Stack different types of transparency in pygame

I have a custom GUI module that uses objects in the tree to manage the interface and transfer them one by one in the correct order.

Now in my objects, I have some surfaces that just have pixel-by-pixel transparency, while others use chroma keys.

My problem is that when blit one surface with pixel-by-pixel transparency on another surface filled with a chroma key, the first surface changes the color of some pixels in the second, which means they are no longer transparent. How can I blend these without getting rid of per-pixel transparency?

Solution

You can convert Surfaces that use chroma keys to use per-pixel transparency before using them >convert_alpha on which blit another per-pixel transparency Surface .


Example:

COLORKEY=(127, 127, 0)
TRANSPARENCY=(0, 0, 0, 0)
import pygame
pygame.init()
screen = pygame.display.set_mode((200, 200))
for x in xrange(0, 200, 20):
  pygame.draw.line(screen, (255, 255, 255), (x, 0),(x, 480))

# create red circle using a colorkey
red_circle = pygame. Surface((200, 200))
red_circle.fill(COLORKEY)
red_circle.set_colorkey(COLORKEY)
pygame.draw.circle(red_circle, (255, 0, 0), (100, 100), 25)

#create a green circle using alpha channel (per-pixel transparency)
green_circle = pygame. Surface((100, 100)).convert_alpha()
green_circle.fill(TRANSPARENCY)
pygame.draw.circle(green_circle, (0, 255, 0, 127), (50, 50), 25)

# convert colorkey surface to alpha channel surface before blitting
red_circle = red_circle.convert_alpha()
red_circle.blit(green_circle, (75, 75))

screen.blit(red_circle, (0, 0))

pygame.display.flip()

Result:

enter image description here

Related Problems and Solutions