ghi
ghi

Reputation: 725

SDL Texture transparent background

This is probably rather simple problem, but after an hour of searching and trying I still didn't manage to solve it. I have two png files. One is a background image and second is foreground. The foreground has an alpha channel. I want to display foreground on top of background.

I'm loading foreground using:

SDL_Surface *clip = SDL_CreateRGBSurface(0, SCREEN_WIDTH, SCREEN_HEIGHT, 32, 0, 0, 0, 0xff);
SDL_Rect rect = { x, 0, SCREEN_WIDTH, SCREEN_HEIGHT };
SDL_BlitSurface(map, &rect, clip, NULL);
*block = SDL_CreateTextureFromSurface(gRenderer, clip);

Where map is some SDL_Surface.

I'm loadin backgroun using:

SDL_Surface* loadedSurface = IMG_Load(path);
//Create texture from surface pixels
SDL_Texture* newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface);
SDL_FreeSurface(loadedSurface);

Then I trying to connect them:

SDL_RenderCopy(gRenderer, background, NULL, &cur);
SDL_RenderCopy(gRenderer, map, NULL, &cur);

But it results in foreground image with black background. What am i doing wrong?

Upvotes: 2

Views: 4004

Answers (1)

Sahib Yar
Sahib Yar

Reputation: 1046

You should add these 2 lines,

Uint32 colorkey = SDL_MapRGB(loadedSurface->format, 0, 0, 0);
SDL_SetColorKey(loadedSurface, SDL_TRUE, colorkey);

before this line in your code

SDL_Texture* newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface);

Upvotes: 4

Related Questions