1

I am trying to achieve transparency in SDL using color keying. While it does work with BMP files, it doesn't with PNG files.

Here is my code:

#include <SDL/SDL.h>
#include <SDL/SDL_image.h>

int main(int argc, char *argv[])
{
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Surface *displaySurface = SDL_SetVideoMode(200, 100, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);

    SDL_Surface *tmpSurface = NULL;
    SDL_Surface *backgroundSurface = NULL;
    SDL_Surface *bmpSurface = NULL;
    SDL_Surface *pngSurface = NULL;

    tmpSurface = IMG_Load("background.png");
    backgroundSurface = SDL_DisplayFormat(tmpSurface);
    SDL_FreeSurface(tmpSurface);

    tmpSurface = SDL_LoadBMP("bmpImage.bmp");
    bmpSurface = SDL_DisplayFormat(tmpSurface);
    SDL_FreeSurface(tmpSurface);
    SDL_SetColorKey(bmpSurface, SDL_SRCCOLORKEY | SDL_RLEACCEL, SDL_MapRGB(bmpSurface->format, 255, 0, 255));

    tmpSurface = IMG_Load("pngImage.png");
    pngSurface = SDL_DisplayFormat(tmpSurface);
    SDL_FreeSurface(tmpSurface);
    SDL_SetColorKey(pngSurface, SDL_SRCCOLORKEY | SDL_RLEACCEL, SDL_MapRGB(pngSurface->format, 255, 0, 255));

    SDL_Rect dest;

    dest.x = 0;
    dest.y = 0;

    SDL_BlitSurface(backgroundSurface, NULL, displaySurface, &dest);

    SDL_BlitSurface(bmpSurface, NULL, displaySurface, &dest);

    dest.x = 50;
    SDL_BlitSurface(pngSurface, NULL, displaySurface, &dest);

    SDL_Flip(displaySurface);

    SDL_Event event;

    while (1) {
        while (SDL_PollEvent(&event)) {
            ;
        }

        SDL_Delay(1);
    }

    return 0;
}

I have uploaded both the code and the images I am using here:

http://tobias.braun-abstatt.de/files/forums/transparency_test.zip

tajmahal
  • 1,665
  • 3
  • 16
  • 29

1 Answers1

2

If you are using SDL_image version 1.2.10 or 1.2.11, make sure to update it to version 1.2.12.

#include <SDL/SDL_image.h>

#if (SDL_IMAGE_MAJOR_VERSION != 1) || (SDL_IMAGE_MINOR_VERSION != 2) || (SDL_IMAGE_PATCHLEVEL < 12)
#error "Invalid SDL_image version"
#endif
  • 1
    SDL and SDL_image are different libraries (at least on Linux). The latest SDL is 1.2.15, the latest SDL_image is 1.2.12. Is it possible to successfully compile on your machine the source code from my answer? –  Mar 01 '12 at 22:51
  • Uh, you are right. I checked the SDL version instead of the SDL_image version by mistake and admittedly did not try your code. Sure enough, the SDL_image version on my system was 1.2.10. Now that I upgraded to 1.2.12, it is working. Thank you! – tajmahal Mar 03 '12 at 20:24