How to draw rectangle with specific color on window using SDL2 in C

1 Answer

0 votes
#include <stdio.h>
#include <stdbool.h>
#include <SDL.h>

int main(int argc, char *argv[]) {
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        printf("SDL_Init Error: %s\n", SDL_GetError());
    }

    SDL_Window *window = SDL_CreateWindow("SDL",
        SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        800, 600, SDL_WINDOW_SHOWN);

    SDL_Surface* screen = SDL_GetWindowSurface(window);
    // windows background color
    SDL_FillRect(screen, NULL, 0xaaccff);

    // ceate rectangle
    SDL_Rect pos;
    pos.x = 30;
    pos.y = 60;
    SDL_Surface* rect = SDL_CreateRGBSurface(0, 225, 200, 32, 0, 0, 0, 0);
    pos.w = rect->clip_rect.w;
    pos.h = rect->clip_rect.h;
    SDL_FillRect(rect, NULL, 0xffeebb);

    // draw 
    if (rect != NULL) {
       SDL_BlitSurface(rect, NULL, screen, &pos);
    }
    SDL_UpdateWindowSurface(window);

    // event loop
    bool close = false;
    while (!close) {
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            switch (event.type) {

            case SDL_QUIT:
                close = true;
                break;
            }
        }
    }

    // free 
    SDL_FreeSurface(rect);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}

 



answered Jan 4, 2022 by avibootz
edited Feb 27, 2022 by avibootz
...