Search code examples
c++sdl-2

What exactly is a renderer in SDL2?


I dont exactly understand what renderer is. Can I have multiple renderers or is there always just one?

For example, how can I draw a rectangle with a certain color on a background with a different color using a renderer?

I believe the answer lies in the functions SDL_RenderDrawRect() and SDL_RenderFillRect(). Am I right?

I know how surfaces and bliting works but I dont know what exactly the renderer symbolizes.

If someone could show me how to draw a rectangle, I think i will understand how renderers work.

So far I have this:

#include <SDL.h>

int main(int argc, char* argv[]) {

    //Initialization
    SDL_Init(SDL_INIT_EVERYTHING);

    //Window
    SDL_Window *MainWindow = SDL_CreateWindow("My Game Window",
                                  SDL_WINDOWPOS_CENTERED,
                                  SDL_WINDOWPOS_CENTERED,
                                  640, 480,
                                  SDL_WINDOW_SHOWN
                                  );

    //Renderer
    SDL_Renderer *Background = SDL_CreateRenderer(MainWindow, -1, 0);

    SDL_SetRenderDrawColor(Background, 255, 255, 255, 255);

    SDL_RenderClear(Background);

    SDL_Delay(3000);

    //Clean up
    SDL_DestroyWindow(MainWindow);
    SDL_Quit();

    return 0;
}

Solution

  • for the first part of your question see this SO question.

    as to why your code doesnt do much:

    you are correct that you need to use either SDL_RenderDrawRect(), or SDL_RenderFillRect(). SDL_RenderDrawRect will draw an unfilled rectangle. SDL_RenderFillRect will be filled (hopefully that is obvious).

    With SDL_renderer you need to call SDL_RenderPresent to copy the "scene" to the screen.

    ...
     //Renderer
    SDL_Renderer* renderer = SDL_CreateRenderer(MainWindow, -1, 0);
    
    SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
    
    SDL_RenderClear(renderer); // fill the scene with white
    
    SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); // the rect color (solid red)
    SDL_Rect rect(0, 0, 100, 50); // the rectangle
    SDL_RenderFillRect(renderer, &rect);
    SDL_RenderPresent(renderer); // copy to screen
    
    SDL_Delay(3000);
    ...