Drawing rectangles

This part will teach you the basics of the coordinate system in SDL( it’s the same for the “old” SDL and SDL2 ). It will also teach you about a new and very important struct, SDL_Rect. You’ll be using it a lot! And finally we’ll draw something!

Note

This part assumes you have SDL2 up and running on your computer, and that you have read the previous part. If you haven’t, please scroll down to part1 and use it to install SDL2 before reading on.

The coordinate system

The SDL coordinate system is defined as ( 0, 0 ) being the ( top, left ). This means that a higher y value means further down.

This also means that if you tell SDL2 to draw a rectangle, you’ll specify the top-left position of the rectangle instead of the bottom left rectangle. More about this later

The basic rectangle

In order to draw something, be it textures or plain rectangles or text or anything, you need a rectangle to specify where to draw it and the size of what you are going to draw. And to hold the size and position we use an SDL_Rect

SDL_Rect

Data members :

• uint16 x – the x position of the rectangle
• uint16 y – the y position of the rectangle
• uint16 w – the width of the rectangle
• uint16 h – the height of the rectangle

And that’s it. It’s a really simple struct, but it’s very important in SDL2 rendering.

Drawing a rectangle

Now you have enough knowledge to draw some rectangles in SDL2. Let’s start off by looking at a the function for rendering a simple rectangle

Parameters

• SDL_Renderer* - the SDL_Renderer we created in the previous part
• SDL_Rect*  - the position and size of the rectangle we want to draw.

Return value

0 on success

Note that it also takes a pointer to the SDL_Rect, and not the SDL_Rect itself.

“But what about the color?” you might ask. Remember how in last function we look at
int SDL_SetRenderDrawColor()? Well, basically, the color you set with this function will also be the color you render your objects with. ( For simplicity, I will refer to this color as SDL_DrawColor from now on. )

And now the fun stuff

Let’s say you have just created and set up your window and renderer like so:

But wait! It’s just a red screen?! As you might have guessed, we forgot to change the color after calling SLD_RenderClear() So the rectangle was drawn with the same color as the background. To make the rectangle visible, we need to change SDL_DrawColor in between SDL_RenderClear() and SDL_RenderDrawRect()

This gives us something like this :

And now we have a nice little rectangle on our screen.

Filling it up…

The function I showed you earlier will only render the edges of the rectangle. What if you want to render the whole rectangle, and not just the edges? Well there is a nearly identical function for that :

Parameters

• SDL_Renderer* - the SDL_Renderer we created in the previous part
• SDL_Rect*  - the position and size of the rectangle we want to draw.

Return value

0 on success

As you can see, the only thing that separates the two us the name. If you switch SDL_RenderDrawRect() with SDL_RenderFillRect() in the example above, you will get the same rectangle with the same color, but this time it will be the whole rectangle and not just the edges.

Conclusion

That’s it for today! Feel free to experiment with two new functions. You can draw as many rectangles as you want, both filled and edges. You can also change the color as often as you want. The only thing you need to remember is to put it all between your SDL_RenderClear( renderer ); and SDL_RenderPresent( renderer );

Have fun! Below is a full working example to experiment with. I have taken the liberty of putting things in different functions to make it easier to read. =)

The comments in the code should explain most of what’s going on. But you need to run the program to really see what’s going on. The code will draw a single blue rectangle on a green background that you can move around on the screen. Don’t worry about the code for moving the player around ( RunGame() ), it’ll be explained in the next post.

Feel free to comment if you have anything to say or ask questions if anything is unclear. I always appreciate getting comments.

You can also email me : olevegard@headerphile.com

64 thoughts on “[ SDL2 – Part 3 ] Drawing rectangles”

1. James says:

Great tutorial series! I appreciate whole work, you’ve made. Keep writing, kepp inspiring! Thanks, bro.

1. olevegard says:

Thank you, positive comments like this helps inspiring me too! I’ve been kinda busy lately, but I’m gonna start writing again very soon.

2. John says:

Hey,this tutorial about SDL2 really helps me a lot.And you made it interesting to me.But in the final code you wrote in part 3,I can’t understand why you create a function called”SetUpRenderer()”,but it’s not used in the program.And I’m confused about these two concepts:
SDL_RenderClear() SDL_RenderPresent()
Could you tell me what’s their difference and how they are related?

1. olevegard says:

Hello

SetupRenderer() is used in the InitEverything() function, at least in the example on this page.

SDL_Clear() basically clears the screen and covers it with the color you have set with SDL_SetRenderDrawColor(). So it basically just removes what we drew the previous frame so that we can render the next frame with a clean, single coloured, background.

SDL_RenderPresent() just updates the screen with what we have drawn this frame.

So basically : SDL_Clear() is used at the beginning of each frame to clear it. And SDL_RenderPresent() is used when we’re down et drawing to get it on the screen.

Hope that helps 🙂

3. David says:

What do you mean by “The code will draw a green-red check board pattern with 2 x 2 tiles inside a blue rectangle. Under the check board, there will be a rectangle that’s twice as long to show that the SDL_Rect doesn’t have to be a square.” Where exactly in the code does this happen? As far as I can see this description doesn’t have any chance of happening as the code only ever renders a green backround with a blue rectangle as the “player” which you can move around with the arrow keys, even setting the color to red makes no sense as you override it with green later. Can you explain what you mean?

Friendly Regards
//David

1. olevegard says:

Hello

Thank you for informing me about this! It’s a typo. I think what happened is that I did have a checkboard like the text said. But then I decided to simplify the code and make it more focused on rendering that one rectangle.

I’ve update with a correct text and changed the code a little. ( Setting the color to red initially didn’t really make much sense as I render it with a green background later. )

Again, thank you. Please tell me if you find other issues 🙂

4. With the help of the LOGO software, you can make the different type of logo as like as Square, rectangle and triangle and many other shapes also. and with that, you can make the benchmark also and it is very helpful.

5. football articles says:
6. I抦 impressed, I need to say. Really rarely do I encounter a blog that抯 both educative and entertaining, and let me tell you, you may have hit the nail on the head. Your thought is excellent; the issue is one thing that not sufficient persons are talking intelligently about. I am very happy that I stumbled throughout this in my seek for one thing referring to this.

1. Thanx very much for helping me.

7. Oh my goodness! an incredible article dude. Thanks Nonetheless I’m experiencing issue with ur rss . Don抰 know why Unable to subscribe to it. Is there anybody getting equivalent rss downside? Anyone who knows kindly respond. Thnkx

8. An fascinating dialogue is value comment. I feel that you must write extra on this subject, it might not be a taboo topic but usually individuals are not sufficient to talk on such topics. To the next. Cheers

10. There are certainly a variety of details like that to take into consideration. That is a nice point to convey up. I provide the ideas above as basic inspiration but clearly there are questions just like the one you deliver up where an important factor will likely be working in honest good faith. I don?t know if finest practices have emerged around issues like that, however I am positive that your job is clearly identified as a good game. Each boys and girls feel the affect of just a moment抯 pleasure, for the remainder of their lives.

11. An fascinating discussion is worth comment. I feel that it’s best to write more on this topic, it may not be a taboo subject but typically persons are not sufficient to speak on such topics. To the next. Cheers

12. That is the precise blog for anybody who desires to find out about this topic. You understand so much its virtually hard to argue with you (not that I actually would need匟aHa). You definitely put a brand new spin on a topic thats been written about for years. Great stuff, simply nice!

13. My developer is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the expenses. But he’s tryiong none the less. I’ve been using Movable-type on several websites for about a year and am nervous about switching to another platform. I have heard great things about blogengine.net. Is there a way I can import all my wordpress content into it? Any kind of help would be really appreciated!

14. Good day! I simply would like to give an enormous thumbs up for the good info you have here on this post. I will be coming again to your blog for more soon.

15. I simply could not depart your site before suggesting that I extremely loved the usual info an individual provide in your guests? Is going to be back often in order to check up on new posts

16. A powerful share, I just given this onto a colleague who was doing a little analysis on this. And he in actual fact purchased me breakfast because I found it for him.. smile. So let me reword that: Thnx for the deal with! However yeah Thnkx for spending the time to debate this, I really feel strongly about it and love studying extra on this topic. If doable, as you turn out to be expertise, would you mind updating your weblog with extra details? It is extremely useful for me. Big thumb up for this blog post!

17. Aw, this was a very nice post. In thought I wish to put in writing like this additionally ?taking time and actual effort to make an excellent article?but what can I say?I procrastinate alot and in no way appear to get one thing done.

18. This is the right blog for anyone who needs to find out about this topic. You realize so much its almost arduous to argue with you (not that I really would need匟aHa). You undoubtedly put a brand new spin on a subject thats been written about for years. Great stuff, simply great!

19. I’m typically to running a blog and i actually respect your content. The article has really peaks my interest. I’m going to bookmark your web site and maintain checking for new information.

20. It’s best to take part in a contest for the most effective blogs on the web. I will advocate this website!

21. You are a great writer thanks.

22. I just saved your site.

23. buca escort hizmetinin artan talebi ile buca çağrı kızlarının sayısı gözle görülür şekilde arttı. Şimdi, birçok sofistike kadın, üniversiteli kız, model kadın, çalışan kadın, ev hanımı ve birinci sınıf toplumdan olgun kadın, buca eskort hizmeti sunmaya başladı . Birçoğu bunu ekmek ve tereyağını kazanmak için tam zamanlı bir iş olarak kabul etti.

24. I抳e read some good stuff here. Definitely worth bookmarking for revisiting. I wonder how much effort you put to create such a excellent informative website.

25. After examine just a few of the weblog posts in your web site now, and I truly like your way of blogging. I bookmarked it to my bookmark website list and shall be checking again soon. Pls try my website as nicely and let me know what you think.

26. The next time I read a blog, I hope that it doesnt disappoint me as much as this one. I imply, I know it was my choice to read, however I truly thought youd have something attention-grabbing to say. All I hear is a bunch of whining about one thing that you possibly can fix when you werent too busy looking for attention.

27. After study a few of the weblog posts in your web site now, and I actually like your way of blogging. I bookmarked it to my bookmark web site listing and might be checking back soon. Pls try my web page as properly and let me know what you think.

28. I was very happy to find this net-site.I needed to thanks to your time for this wonderful read!! I undoubtedly enjoying every little little bit of it and I’ve you bookmarked to check out new stuff you blog post.

29. Thanks a lot for sharing this with all people you really realize what you’re talking about! Bookmarked. Please also discuss with my site =). We could have a link exchange agreement among us!

30. With havin so much content do you ever run into any issues of plagorism or copyright infringement? My site has a lot of unique content I’ve either authored myself or outsourced but it looks like a lot of it is popping it up all over the internet without my authorization. Do you know any techniques to help reduce content from being stolen? I’d certainly appreciate it.

31. A powerful share, I just given this onto a colleague who was doing a little bit analysis on this. And he actually bought me breakfast because I found it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to discuss this, I really feel strongly about it and love reading extra on this topic. If potential, as you turn into expertise, would you thoughts updating your blog with extra details? It’s extremely helpful for me. Massive thumb up for this weblog post!

32. Thanks so much for sharing the info. I love sucking dick btw hmu

33. Has anybody ever shopped at West End Vapor Vape Shop in 415 Mary Esther Cutoff, Suite E?

34. I definitely wanted to write down a brief word to be able to thank you for all of the remarkable strategies you are giving out at this site. My particularly long internet search has at the end been compensated with reliable tips to go over with my two friends. I ‘d suppose that most of us visitors actually are extremely blessed to be in a magnificent network with many awesome people with useful secrets. I feel very fortunate to have seen the web pages and look forward to some more amazing minutes reading here. Thanks again for everything.

35. I in addition to my buddies have already been viewing the good points found on your web blog then before long came up with a horrible suspicion I had not thanked the website owner for them. The men are already for this reason stimulated to read through them and have now sincerely been loving them. We appreciate you being well considerate and also for making a decision on variety of awesome subjects millions of individuals are really eager to be aware of. Our own honest regret for not saying thanks to earlier.

36. I must get across my appreciation for your kind-heartedness giving support to people that should have guidance on that study. Your special commitment to passing the message up and down turned out to be exceedingly insightful and has in every case encouraged guys and women just like me to reach their objectives. This informative instruction can mean this much to me and additionally to my office workers. Thanks a lot; from everyone of us.

37. A down jacket’s fit can be dependent on a number of factors including the weight of the jacket, the length of the jacket, and the material it’s made out of. Some of the best down jacket for men, like the Montane Down Jacket, have a very low rise.