SDL 纹理透明背景

SDL Texture transparent background

本文关键字:背景 透明 纹理 SDL      更新时间:2023-10-16

这可能是一个相当简单的问题,但是经过一个小时的搜索和尝试,我仍然无法解决它。我有两个 png 文件。一个是背景图像,第二个是前景。前景有一个 alpha 通道。我想在背景顶部显示前景。

我正在使用以下内容加载前台:

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);

地图是一些SDL_Surface。

我正在使用以下内容加载背景:

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

然后我尝试连接它们:

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

但它会产生带有黑色背景的前景图像。我做错了什么?

你应该添加这 2 行,

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

在代码中的此行之前

SDL_Texture* newTexture = SDL_CreateTextureFromSurface(gRenderer, loadedSurface);