在我的 SDL2 应用程序中,我尝试加载 png 图像(透明)。我想用 SDL2 为该图像提供背景颜色,因为我想在程序中的其他地方重用该图像,并且我不想拥有同一图像的多个版本。
如何使用 SDL2 为 SDL_Surface* 或 SDL_Texture* 提供背景颜色?
OS : Windows
Text Editor : VScode
Building Mehtod : Makefile
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
int main(int argc, char* argv[]){
SDL_Init(SDL_INIT_EVERYTHING);
IMG_Init(IMG_INIT_PNG);
SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
SDL_CreateWindowAndRenderer(900, 500, SDL_WINDOW_RESIZABLE, &window, &renderer);
SDL_SetWindowTitle(window, "StackOverflowApp");
SDL_Surface* surface = IMG_Load("./yourImage.png");
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_Event event;
bool run = true;
while (run) {
if(SDL_PollEvent(&event)) {
if(event.type == SDL_QUIT) {
run = false;
}
}
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
}
SDL_FreeSurface(surface);
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return EXIT_SUCCESS;
}
all:
@cls
g++ -I src/include -L src/lib -std=c++23 -o main main.cpp -lmingw32 -lSDL2main -lSDL2 -lSDL2_image
./main
解决方案如下:
要为透明图像提供背景颜色,您需要在创建纹理之前用所需的背景颜色填充图像的表面。以下是实现这一目标的方法:
SDL_FillRect
用您想要的背景颜色填充新表面。这是代码的修改版本,演示了这一点:
#include <iostream>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
int main(int argc, char* argv[]){
SDL_Init(SDL_INIT_EVERYTHING);
IMG_Init(IMG_INIT_PNG);
SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
SDL_CreateWindowAndRenderer(900, 500, SDL_WINDOW_RESIZABLE, &window, &renderer);
SDL_SetWindowTitle(window, "StackOverflowApp");
SDL_Surface* loadedSurface = IMG_Load("./yourImage.png");
// Create a new surface with the same dimensions as the loaded image
SDL_Surface* backgroundSurface = SDL_CreateRGBSurface(0, loadedSurface->w, loadedSurface->h, 32, 0, 0, 0, 0);
// Fill the new surface with a color, for instance, white
SDL_FillRect(backgroundSurface, NULL, SDL_MapRGB(loadedSurface->format, 255, 255, 255));
// Blit (copy) the loaded image onto the background
SDL_BlitSurface(loadedSurface, NULL, backgroundSurface, NULL);
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, backgroundSurface);
SDL_Event event;
bool run = true;
while (run) {
if(SDL_PollEvent(&event)) {
if(event.type == SDL_QUIT) {
run = false;
}
}
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
}
SDL_FreeSurface(loadedSurface);
SDL_FreeSurface(backgroundSurface);
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return EXIT_SUCCESS;
}
在上面的代码中,我们创建一个新的表面(
backgroundSurface
)并用白色填充它。之后,我们将 loadedSurface
(您的透明 PNG 图像)传输到 backgroundSurface
上。生成的纹理将是带有白色背景的 PNG 图像。调整SDL_MapRGB
中的RGB值来改变背景颜色。