Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw a square with SDL 2.0?

Tags:

c

sdl

sdl-2

I would like to do something simple like draw a square on the screen using C and SDL. The example that I copied is not working.

//Get window surface
SDL_Surface *screenSurface = SDL_GetWindowSurface(window);

//Fill the surface white
SDL_FillRect(screenSurface, NULL, SDL_MapRGB(screenSurface->format, 0xFF, 0xFF, 0xFF));

//create a square
SDL_FillRect(screenSurface, SDL_Rect(0,0,100,100), SDL_MapRGB(screenSurface->format, 0x00, 0x00, 0x00));

It correctly fills the screen white, but fails on the call to SDL_Rect:

error: expected expression before ‘SDL_Rect’

How do I correctly draw a square using SDL 2.0?

like image 634
Andrew Avatar asked Nov 01 '13 16:11

Andrew


People also ask

How do you draw a line in SDL?

SDL_RenderDrawLine() draws the line to include both end points. If you want to draw multiple, connecting lines use SDL_RenderDrawLines() instead.


2 Answers

SDL_FillRect does not take an SDL_Rect as an argument; it takes a pointer to SDL_Rect.

//Create a square
SDL_Rect rect(0,0,100,100);
SDL_FillRect(screenSurface, &rect, SDL_MapRGB(...))

That is why when you fill with white you can pass NULL to the function. NULL is not of type SDL_Rect, but it is a pointer, so the compiler is fine with it.

like image 141
Zach Stark Avatar answered Sep 20 '22 01:09

Zach Stark


As mentioned by Zach Stark, SDL_FillRect does not take an SDL_Rect as an argument. Rather, it takes a pointer to an SDL_Rect. By prefixing the variable with an ampersand (&), you pass only a reference (a pointer) to the original variable. However, I could not get Zach's code sample to work in my C program. The following uses a different syntax for creating an SDL_Rect but it worked for me.

// create a black square
SDL_Rect rect = {0, 0, 100, 100}; // x, y, width, height
SDL_FillRect(screenSurface, &rect, SDL_MapRGB(screenSurface->format, 0x00, 0x00, 0x00));
like image 28
Andrew Avatar answered Sep 17 '22 01:09

Andrew