Cloud Stack Ninja

I want to change the colour of a rect dynamically during runtime. Currently set_colour is filling all of the pixels of the surface with a single colour value. This works, but an issue arises when a method like set_outline is called, which modifies the transparency of the surface.

class Rectangle(pg.sprite.Sprite):
    def __init__(self):
        pg.sprite.Sprite.__init__(self)
        self.original_image = pg.Surface((10, 10))
        self.image = self.original_image
        self.rect = self.image.get_rect()

    def set_colour(self, colour_value):
        self.colour = colour_value
        self.image.fill(self.colour)
        self.original_image.fill(self.colour)

    def set_outline(self, thickness):
        self.thickness = thickness
        size = self.image.get_size()

        calc = thickness/100
        p_width, p_height = size[0], size[1]
        width, height = size[0]*calc, size[1]*calc

        self.image = self.image.convert_alpha()

        center_x, center_y = (p_width//2)-(width//2), (p_height//2)-(height//2)
        pg.draw.rect(self.image, (0, 0, 0, 0), (center_x, center_y, width, height))

Now if I try to change the colour of that rect during runtime, it will overwrite all of those transparent pixels created in set_outline.

Is there a way to mask or blend the colour on to the rect, so it's not replacing any of the transparency?



Read more here: https://stackoverflow.com/questions/64190277/changing-colour-of-a-surface-without-overwriting-transparency

Content Attribution

This content was originally published by Hydra at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: