I just need someone to explain how to do it as I am very confused.
I think what you need to do is make a surface and a rect. And that is the extent to which I understand how to draw things to a screen in SDL.
I just need someone to explain how to do it as I am very confused.
I think what you need to do is make a surface and a rect. And that is the extent to which I understand how to draw things to a screen in SDL.
If all you want to do is draw some rects, you don’t need any surfaces; what you do need is:
A window and a renderer for that window can be made using SDL_CreateWindowAndRenderer
. Then, anything that you use the renderer to display will be shown in the window.
Rects are rendered by a renderer by first selecting the colour of the rect (using SDL_SetRenderDrawColor
), then instructing the renderer to draw the rect using SDL_RenderDrawRect
.
I’ve included a full working example below. This example displays a black window with a red rect in it. This example does a few extra things that are very common to do when using SDL:
The call to SDL_RenderPresent is the part that communicates to the renderer “okay, show me everything I’ve told you to draw;” without it, the renderer will accept all of your draw commands but not actually do anything visible.
My example does not have any error handling in it: most of the SDL functions used in the example have a return value that can be checked to find out if an error has occurred. For a simple example like this, I decided to omit error checking to make the intent of the code a little clearer.
The example compiles on my computer using the command:
cc example.c -lSDL2 -o example
Running ./example
produces a window with the following content:
You might be interested in the Lazy Foo’ SDL Tutorials, which cover subjects like setting up an SDL-based project and displaying output in windows. I also highly recommend the SDL wiki, for when you aren’t sure what a particular function does.
#include <SDL2/SDL.h>
int main() {
SDL_Init(SDL_INIT_VIDEO);
SDL_Window *window;
SDL_Renderer *renderer;
Uint32 flags = 0;
SDL_CreateWindowAndRenderer(800, 600, flags, &window, &renderer);
SDL_Rect rect = {
.x = 100,
.y = 100,
.w = 100,
.h = 100
};
int running = 1;
while (running) {
SDL_Event e;
while (SDL_PollEvent(&e)) {
if (e.type == SDL_QUIT) {
running = 0;
}
}
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderDrawRect(renderer, &rect);
SDL_RenderPresent(renderer);
SDL_Delay(1000/60);
}
}