Tuesday, July 12, 2011

SDL: Color Keys (Transparency)

A few times you’ll have portions of the image not to  be visible when you blit.  This is done by setting a transparent color key. You can select a single color that will be ignored when blitting.


To set a color key,  use the SDL_SetColorKey function.

int SDL_SetColorKey(SDL_Surface *surface, Uint32 flag, Uint32 key);


This function returns an int. In typical SDL style, 0 means success and -1 means an error. The function has three parameters—a pointer to the surface for which you are setting the color key (surface), a set of
flags (flag), and a value to use as the transparent color (key). There are two different flags that you can use in the flag parameter. One is SDL_SRCCOLORKEY, and the other is SDL_RLEACCEL. The
SDL_RLEACCEL flag is not used by itself, so you have three different values that you can pass in the flag parameter: 0, SDL_SRCCOLORKEY, and SDL_SRCCOLORKEY | SDL_RLEACCEL.
If you pass a 0, then any color key you might have had on that surface will be cleared. If you pass SDL_SRCCOLORKEY, the key holds the value that will be set as the transparent color. The color has to be in the native pixel format, so it is a good idea to use SDL_MapRGB here. If you pass SDL_SRCCOLORKEY | SDL_RLEACCEL, you set the color key and set up the surface to use RLE (Run Length Encoded) acceleration. (In other words, you encode the image so it blits faster by skipping
over transparent pixels.)


If you ever need to know whether the source color key is set for a surface, you can examine the flags member of the SDL_Surface representing it. SDL_SRCCOLORKEY will be present if there is a color key. Similarly,
SDL_RLEACCEL will be present if you specified RLE acceleration. If SDL_SRCCOLORKEY is present, the color key member of the surface’s pixel format will have the color key.

Here is a program to clearify the above mentioned concepts:


#include <sdl/sdl.h>
#include "sdl_image.h"

SDL_Surface *screen=NULL;
SDL_Surface *image=NULL;
Uint32 trans_Color;
int main(int argc, char* argv[])
{
    char done;

    SDL_Init(SDL_INIT_VIDEO);

    screen=SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);

    image=IMG_Load("image.png");

    trans_Color=SDL_MapRGB(image->format,0,0,255);

    SDL_SetColorKey( image, SDL_SRCCOLORKEY,trans_Color);

    if(image==0)

    {

    return(1);

    }
    done = 0;

    SDL_Rect pos;

    pos.x=0;

    pos.y=0;

    SDL_Event event;

    while(done!=1)
    {


        while(SDL_PollEvent(&event))
        {


            if(event.type ==SDL_QUIT)
            {


                done=1;


            }
        }


        //apply image to screen
        SDL_BlitSurface(image, 0, screen, &pos);
        //Update screen
        SDL_Flip(screen);
    }

    SDL_Quit();

    return(0);
}

The source code is available for download at:

No comments:

Post a Comment