1
正如你可以看到下面有BMP图像,但其背景颜色为白色:SDL BMP图像背景
我怎样才能改变它是例如黑色(不编辑BMP图像本身)?
这里我有代码显示在窗口的BMP图像:
#include <iostream>
#include "SDL.h"
using namespace std;
int main(int argc, char *args[])
{
SDL_Window *window = nullptr;
SDL_Renderer *renderer = nullptr;
SDL_Surface *surface = nullptr;
SDL_Texture *texture = nullptr;
SDL_Event event;
SDL_Rect positionRect;
SDL_Rect dimensionRect;
positionRect.x = 0;
positionRect.y = 0;
positionRect.w = 100;
positionRect.h = 100;
dimensionRect.x = 0;
dimensionRect.y = 0;
dimensionRect.w = 300;
dimensionRect.h = 300;
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s", SDL_GetError());
return 1;
}
if (SDL_CreateWindowAndRenderer(500, 500, SDL_WINDOW_OPENGL, &window, &renderer)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window and renderer: %s", SDL_GetError());
return 1;
}
surface = SDL_LoadBMP("sample.bmp");
if (!surface) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create surface from image: %s", SDL_GetError());
return 1;
}
texture = SDL_CreateTextureFromSurface(renderer, surface);
if (!texture) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create texture from surface: %s", SDL_GetError());
return 1;
}
SDL_FreeSurface(surface);
surface = nullptr;
while (1) {
SDL_PollEvent(&event);
if (event.type == SDL_QUIT) {
break;
}
//SDL_SetRenderDrawColor(renderer, 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00);
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, &positionRect, &dimensionRect);
SDL_RenderPresent(renderer);
}
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
我猜,改变图像实际上是实现这一点最简单的方法。但是如果真的有必要在你的应用程序中完成。那么请查看** ['SDL_Surface'](https://www.libsdl.org/release/SDL-1.2.15/docs/html/sdlsurface.html)**。您可以访问像素数据并用黑色像素替换白色像素。 AFAIK,BMP中没有背景颜色。每个像素都有任何颜色。 “背景”颜色只存在于你的感知中...... – Scheff
这并非完全无关紧要。你可以修改'SDL_LoadBmp'返回的'SDL_Surface',但我不认为你可以天真地将白色转换为黑色(查看人物眼睛的颜色)。你coudl写一个洪水填充功能,但修改图像可能是最简单的。你也可能发现,简单地将它放到黑色背景上会导致它看起来不太好;毕竟它是以故意的黑色边框绘制的! – Rook
你可以设置一个颜色键,sdl会使这个颜色透明:http://lazyfoo.net/SDL_tutorials/lesson05/index.php – Lanting