What is Colour Keying?
- Removing a certain colour from an image.
Why would we want to remove colours from our images?
- To remove unnecessary backgrounds from your images.
Take a look at these two pictures, here's the one without Colour Keying:
With Colour Keying:
As you can see, our circle has a pink background without Colour Keying, however if we do use it, it removes the pink colour.
A tip when making sprites is to use a background colour that isn't used much such as R: 255 G: 0 B: 255. This pink colour has become a standard in sprites as it is not a very attractive shade of pink.
Anyway, enough of me babbling, lets get to the code. For this tutorial, you will need to have already setup 'SDL_Image', there are numerous tutorials around the internet. Please note I am only going to give you the function to load the image not the setup of SDL.
First we need to make the function declaration
Code: Select all
SDL_Surface* loadImage(const char* filename) {
Code: Select all
SDL_Surface* o;
o = IMG_Load(filename.c_str());
surface = SDL_DisplayFormat(o);
SDL_FreeSurface(o);
SDL_SetColorKey(surface, SDL_SRCCOLORKEY | SDL_RLEACCEL, 0xFF00FF);
return surface;
The next line is the important bit, we set the colour key by calling SDL_SetColorKey, the first parameter is the surface, the second is the flag, the only thing you need to know is to type in both those flags. The third parameter is the color you want to remove, in my case it is 0xFF00FF with translates to (255, 0, 255). An easier and more understandable way to set the colour, would be to do this:
Code: Select all
Uint32 colourkey = SDL_MapRGB(surface->format(), 255, 0, 255);
SDL_SetColorKey(surface, SDL_SRCCOLORKEY | SDL_RLEACCEL, colourkey);
return surface;
Code: Select all
SDL_Surface* myimage = loadImage("myimage.bmp/png/etc...");