SDL bmp image background

1

As you can see below there is bmp image but its background color is white:

enter image description here

How can i change it to be for example black (without editing the bmp image itself)?

Here I have code to show bmp image on window:

#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;
}
c++
sdl-2
bmp
asked on Stack Overflow Jun 13, 2017 by Silidrone • edited Jun 13, 2017 by genpfault

1 Answer

2

You should add these 2 lines,

Uint32 colorkey = SDL_MapRGB(surface->format, 255, 255, 255);
SDL_SetColorKey(surface, SDL_TRUE, colorkey);

before this line in your code

texture = SDL_CreateTextureFromSurface(renderer, surface);
answered on Stack Overflow Aug 1, 2017 by Sahib Yar

User contributions licensed under CC BY-SA 3.0