Search code examples
sdlsdl-2color-depth

8 Bit Surfaces in SDL 2


Originally in SDL, the following code could be used to setup a surface:

SDL_Surface *screen = SDL_SetVideoMode(800, 600, 8, 0);

Now, in SDL2 the following code must be used:

SDL_Window *window = SDL_CreateWindow("Title", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, 0);
SDL_Surface *surface = SDL_GetWindowSurface(window);

My problem is that SDL_CreateWindow offers no way to set the bbp of the window or surface. It seems to default to 32 bit. I've tried using SDL_ConvertSurfaceFormat but surface->format->BitsPerPixel stays at 32.

How can I create a 8 bit surface in SDL 2? I realize I will need a color palette.


Solution

  • Use SDL_CreateRGBSurface where you can specify number of bits.

    Example:

    SDL_Window *sdlWindow;
    SDL_Renderer *sdlRenderer;
    SDL_CreateWindowAndRenderer(0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP, &sdlWindow, &sdlRenderer);
    
    SDL_Surface *screen = SDL_CreateRGBSurface(0, 640, 480, 32,
                                        0x00FF0000,
                                        0x0000FF00,
                                        0x000000FF,
                                        0xFF000000);
    SDL_Texture *sdlTexture = SDL_CreateTexture(sdlRenderer,
                                            SDL_PIXELFORMAT_ARGB8888,
                                            SDL_TEXTUREACCESS_STREAMING,
                                            640, 480);
    
    SDL_UpdateTexture(sdlTexture, NULL, screen->pixels, screen->pitch);
    SDL_RenderClear(sdlRenderer);
    SDL_RenderCopy(sdlRenderer, sdlTexture, NULL, NULL);
    SDL_RenderPresent(sdlRenderer);