DEV Community

Noah11012
Noah11012

Posted on • Updated on

Using SDL2: Drawing Rectangles

Along with the new 2D hardware accelerated API in SDL2, we can draw primitive shapes like rectangles. Two functions, SDL_RenderDrawRect() and SDL_RenderFillRect() are functions that can be used to draw rectangles on the screen. The difference between the two will be discussed later.

Both of these functions take a pointer to an SDL_Rect for its position and dimensions. Because both are apart of the hardware rendering API, each takes a pointer to an SDL_Renderer.

SDL_RenderDrawRect() draws the outline of a rectangle while SDL_RenderFillRect draws a rectangle filled.

Before we draw any rectangles to the screen, we can change the color it will use with SDL_SetRenderDrawColor() which takes four arguments:

  • An SDL_Renderer
  • Red value from 0-255
  • Green value from 0-255
  • Blue value from 0-255
  • Alpha value from 0-255

Reusing the Application class from before the Pong series, we have the following code:

void Application::draw()
{
    SDL_RenderClear(m_window_renderer);

    SDL_Rect rect;
    rect.x = 250;
    rect.y = 150;
    rect.w = 200;
    rect.h = 200;

    SDL_SetRenderDrawColor(m_window_renderer, 255, 255, 255, 255);
    SDL_RenderDrawRect(m_window_renderer, &rect);

    SDL_SetRenderDrawColor(m_window_renderer, 0, 0, 0, 255);

    SDL_RenderPresent(m_window_renderer);
}
Enter fullscreen mode Exit fullscreen mode

Compile and run.

For the filled version is just as simple:

void Application::draw()
{
    ...
    SDL_RenderFillRect(m_window_renderer, &rect);

    ...

    SDL_RenderPresent(m_window_renderer);
}
Enter fullscreen mode Exit fullscreen mode

Compile and run.

In addition to rectangles, SDL2 supports two other primitives. Namely, lines and points.

We will take a look at both quickly.

SDL_RenderDrawLine():

  • SDL_Renderer
  • x value for the beginning point
  • y value for the beginning point
  • x value for the end point
  • y value for the end point

SDL_RenderDrawPoint():

  • SDL_Renderer
  • x value for the position
  • y value for the position

What's next

For the next post, we will learn how to manipulate the viewport to render certain parts of the world.

Github repository: https://github.com/Noah11012/sdl2-tutorial-code

Discussion (1)

Collapse
blakeb211 profile image
Blake

If I used SDL_HARDWARE_ACCELERATED to get my renderer, do I get more benefits of the hardware acceleration by batching the primitives I draw? For example using RenderDrawLines and RenderDrawRects calls with things batched? Separate but related--Is there any way to tell that I'm actually getting a hardware acceleration?