I upload a PNG file (with some transparent places) to my SDL application.
Googling on how to do this provided me with this sample code:
SDL_Surface *LoadImage(std::string filename)
{
SDL_Surface* loaded_image = 0, compatible_image = 0;
if (!filename.c_str())
return 0;
loaded_image = IMG_Load(filename.c_str());
if (!loaded_image)
return 0;
compatible_image = SDL_DisplayFormat(loaded_image);
SDL_FreeSurface(loaded_image);
return compatible_image;
}
But when the line is reached compatible_image = SDL_DisplayFormat(loaded_image);, the application stops with a fatal exception (it try { /* ... */ } catch (...) { /* ... */ }does not even help). Replace SDL_DisplayFormat()with SDL_DisplayFormatAlpha()also did not help. So, I just deleted the lines causing the exception and downloaded this code to load the images:
SDL_Surface *LoadImage(std::string filename)
{
if (!filename.c_str())
return 0;
return IMG_Load(filename.c_str());
}
And I found such an unpleasant thing: when some sprite overlays the transparent pieces of another, artifacts appear. Something like that:


I am animating my “hero” with this simple algorithm:
// SDL_Surface sprite = LoadImage("hero.bmp");
// hero.bmp contains animation frames followed one-by-one in a single line
// spriteFrameCnt is a number of animation frames
// spriteWidth and spriteHeight contain single frame params
SDL_Rect srcRect;
srcRect.x = spriteFrame * spriteWidth;
srcRect.w = spriteWidth;
srcRect.y = 0;
srcRect.h = spriteHeight;
spriteFrame = ++spriteFrame % spriteFrameCnt;
SDL_BlitSurface(sprite, &srcRect, screen, &rcSprite);
How can this be explained and fixed?