pythonpython-3.xpygame

Invert colors of a mask in pygame?


I have a pygame mask of a text surface that I would like to invert, in the sense that the black becomes white, and the white becomes black. The black is the transparent part of the text, and the white is the non-transparent part, but I'd like it flipped so I can make a text outline. I can't really figure it out. If anyone knows, it would be much appreciated

Ill attach the code that generates and blits the mask :)

        location_text = self.font.render(self.location, True, self.text_color)
        pos = ((screen_width - location_text.get_width()) / 2, 320)        

        mask = pygame.mask.from_surface(location_text)
        mask_surf = mask.to_surface()
        mask_surf.set_colorkey((0, 0, 0))

        screen.blit(mask_surf, (pos[0], pos[1]))

enter image description here


Solution

  • There are different possibilities. You can invert the mask with invert.

    mask = pygame.mask.from_surface(location_text)
    mask.invert()
    mask_surf = mask.to_surface()
    mask_surf.set_colorkey((255, 255, 255))
    

    You can also set the colors when you turn the mask into a surface. Make the setcolor black and the unsetcolor white (see to_surface()):

    mask = pygame.mask.from_surface(location_text)
    mask_surf = mask.to_surface(setcolor=(0, 0, 0, 0), unsetcolor=(255, 255, 255, 255))