SDL bmp图像背景

时间:2017-06-13 04:51:25

标签: c++ sdl-2 bmp

如下所示,有bmp图像,但背景颜色为白色:

enter image description here

如何将其更改为黑色(不编辑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;
}

1 个答案:

答案 0 :(得分:2)

你应该添加这两行,

Uint32 colorkey = SDL_MapRGB(surface->format, 255, 255, 255);
SDL_SetColorKey(surface, SDL_TRUE, colorkey);
在代码中的这一行之前

texture = SDL_CreateTextureFromSurface(renderer, surface);