2
votes

I'm making a game that only uses PNG with black and white pixels. But there are some times where I would want to change the color of the white pixels to something different, like green (#00FF00).

How would I go about doing this exactly?

EDIT: Okay, I figured out a solution

Here is a simple function to do so:


    void setColor(SDL_Surface *surface, SDL_Color color) {
        Uint16 *pixels = (Uint16 *) surface->pixels;            // Get the pixels from the Surface

        // Iterrate through the pixels and chagne the color
        for (int i = 0; i w * surface->h); i++) {
            if (pixels[i] == SDL_MapRGB(surface->format, 0xFF, 0xFF, 0xFF))        // Search for white pixels
                pixels[i] = SDL_MapRGB(surface->format, color.r, color.b, color.g);
        }
    }

Something to keep in mind, change the "Uint16" to "Uint32" if you are using a 32-Bit surface, or "Uint8" for a 8-Bit surface.

I'm not sure on how fast this code is, but it gets the job done.

1
This is how it is done, works with all bit depths, alpha and so on. - Valmond

1 Answers

0
votes

That depends on exactly what you're trying to set the color of.

Without more information, two APIs that come immediately to mind are "SDL_SetColors()" and "SDL_SetPalette()".

But the real answer is "it depends".