Monday, May 20, 2024
HomeGame Developmentsdl2 - How can I directly write pixel data in an SDL...

sdl2 – How can I directly write pixel data in an SDL window using surfaces?


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;
}

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments