Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a white surface with the shape of my original image in pygame?

I am making a game in python using pygame. I have an image, and I used set_colorkey() for the color (0,0,0). I did not add alpha channel. It works fine.

I want to add a white transparent surface on it when it is selected. I used the following code, but it makes the corners of the image white, too. How can I add a white surface which has the shape of the main image?

window.blit(obj.get_image(),obj.get_pos())
if obj.selected:
    white_surface = pygame.Surface(obj.size,pygame.SRCALPHA)
    white_surface.fill((255,255,255))
    white_surface.set_alpha(128)
    window.blit(white_surface,obj.get_pos())

From my game:

What I want:

like image 997
labaluba Avatar asked Oct 31 '25 21:10

labaluba


1 Answers

Create a pygame.Mask form the surface and convert the mask to a white shape. A mask can be created with pygame.mask.from_surface. The pygame.Mask can be converted to a black and white pygame.Surface with the to_surface method:

def create_white_surf(surf, alpha):
    mask = pygame.mask.from_surface(surf)
    white_surface = mask.to_surface()
    white_surface.set_colorkey((0, 0, 0))
    white_surface.set_alpha(alpha)
    return white_surface

See also Selection and highlighting


Minimal example:

repl.it/@Rabbid76/PyGame-PyGame-HighlightObject

import pygame

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

class TestObject:
    def __init__(self, x, y):
        self.image = pygame.Surface((64, 64), pygame.SRCALPHA)
        pygame.draw.circle(self.image, (0, 0, 0), (32, 32), 32)
        pygame.draw.rect(self.image, (0, 0, 0), (0, 0, 32, 64))
        pygame.draw.circle(self.image, (0, 128, 0), (32, 32), 30)
        pygame.draw.rect(self.image, (0, 128, 0), (2, 2, 30, 60))
        self.rect = self.image.get_rect(center = (x, y))
        self.size = self.rect.size
        self.selected = False
    def get_image(self):
        return self.image
    def get_pos(self):
        return self.rect.topleft

def create_white_surf(surf, alpha):
    mask = pygame.mask.from_surface(surf)
    white_surface = mask.to_surface()
    white_surface.set_colorkey((0, 0, 0))
    white_surface.set_alpha(alpha)
    return white_surface

obj_list = [TestObject(100, 150), TestObject(200, 150)]

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False    
    for obj in obj_list:
        obj.selected = obj.rect.collidepoint(pygame.mouse.get_pos())      

    window.fill((127, 127, 128))

    for obj in obj_list:
        window.blit(obj.get_image(), obj.get_pos())
        if obj.selected:
            white_surf = create_white_surf(obj.get_image(), 128)
            window.blit(white_surf, obj.get_pos())

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
exit()
like image 142
Rabbid76 Avatar answered Nov 03 '25 09:11

Rabbid76