2
\$\begingroup\$

I'd like to directly modify pixels in my window in SDL 2. I expect this code to display an entirely red window, but instead I'm getting an all black window.

I'm able to get it working if I directly write to window_surface with the same technique, but not by blitting another surface. I'd like to get it working this way at least just for the purposes of understanding.

#include <SDL.h>

int main()
{
    SDL_Init(SDL_INIT_EVERYTHING);

    SDL_Window *window = SDL_CreateWindow("Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1600, 900, 0);

    SDL_Surface *window_surface = SDL_GetWindowSurface(window);

    SDL_Surface *canvas = SDL_CreateRGBSurfaceWithFormat(
        0, 1600, 900, 32, SDL_PIXELFORMAT_RGBA8888
    );

    Uint32 *buffer = (Uint32*) canvas->pixels;
    int row    = 0;
    int column = 0;
    int offset;
    Uint32 color;
    SDL_UnlockSurface(canvas);
    while (row < 900)
    {
        column = 0;
        while (column < 1600)
        {
            offset = row * 1600 + column;
            color = SDL_MapRGBA(canvas->format, 255, 0, 0, 255);
            buffer[offset] = color;
            column++;
        }
        row++;
    }
    SDL_LockSurface(canvas);

    int quit = 0;
    SDL_Event event;
    while (!quit)
    {
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT)
            {
                quit = 1;
            }
        }

        SDL_BlitSurface(canvas, 0, window_surface, 0);
        SDL_UpdateWindowSurface(window);

        SDL_Delay(10);
    }

    SDL_Quit();

    return 0;
}

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

It's the other way around, first you call SDL_LockSurface(canvas); then SDL_UnlockSurface(canvas); Just swap those two lines and it works.

\$\endgroup\$
1
  • \$\begingroup\$ Is the "canvas" surface even needed? Can you not use the "window_surface" directly and skip the blitting? \$\endgroup\$
    – Haydentech
    Commented Jun 8 at 20:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .