Advertisement

Drawing a rectangle in SDL

Started by October 22, 2021 03:28 PM
2 comments, last by stderr 3 years, 3 months ago

Hi all.

I've just started to play around with SDL2 and have run into some problems(?) right away. I'm trying to draw a rectangle but it doesn't work as expected. The right side gets shorter than the left one, and there is a gap in the lower right corner. Is this not a good way to draw a rectangle?

Any help would be greatly appreciated.


/* gcc -o sdl-test sdl-test.c `pkg-config --cflags --libs sdl2` */

#include <stdio.h>
#include <stdlib.h>

#include <SDL.h>

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

	SDL_Window *win;
	SDL_Renderer *rdr;
	SDL_Rect rect[] = {
		{ 100, 100, 50, 50 },
		{ 101, 101, 48, 48 },
		{ 102, 102, 46, 46 },
		{ 103, 103, 44, 44 },
	};

	SDL_Init(SDL_INIT_VIDEO);
	win = SDL_CreateWindow("Rect", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
	rdr = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
	SDL_SetRenderDrawColor(rdr, 0xff, 0xff, 0xff, SDL_ALPHA_OPAQUE);
	SDL_RenderDrawRects(rdr, rect, 4);
	SDL_RenderPresent(rdr);
	SDL_Delay(10000);

	return EXIT_SUCCESS;
}

My first bit of advice would be to not bother with the SDL renderer at all. It's buggy (as you noticed), but it's also just plain not powerful enough for a modern 2D game. Or even a retro 2D games with a few semi-modern touches.

That said, no, this is not a good way of rendering rectangles. Especially if you want rectangles with thick lines, prefer SDL_RenderFillRects over SDL_RenderDrawRects. If you want an unfilled rectangle, just draw each of the four sides of your unfilled rectangle as a filled rectangle. This should allow you to sidestep the bugs in the SDL renderer (which are mostly related to line primitives), and it probably has better performance as well.

Advertisement

@a light breeze Thanks man.

Meanwhile I've also tried DrawLines with horrible results too. Really off-putting and I will never, never, never ever use SDL again.

This topic is closed to new replies.

Advertisement