Rendering Simple Shapes with SFML
SFML is not all about window-creation (even though many people use it only for that). It can be used to render hardware-accelerated graphics (including some basic as well as complex shapes). In this example, we’ll constrain ourselves to draw a basic shape (a circle):-
CPP
#include <SFML/Graphics.hpp> int main() { sf::RenderWindow window( sf::VideoMode(640, 480), "Hello World"); sf::CircleShape shape(200); while (window.isOpen()) { sf::Event event; while ( window.pollEvent(event)) if (event.type == sf::Event::Closed) window.close(); window.clear(); window.draw(shape); window.display(); } return 0; } |
This would produce the following output:- Explanation:
- Note: RenderWindow has been used instead of Window. This is particularly because we are rendering something in the window. The Window class is actually meant for OpenGL programmers or anyone who simply wants to create and draw a window! If we have to render something on the window we have to use RenderWindow class. The fundamental difference between the two is just this that one is meant for simply creating a blank window for context-creation and other is specifically for 2D rendering which you can’t use outside of SFML.
- Moving on from RenderWindow, in line 06 we create a circle shape and pass in a radius of 100. Now exactly after the event loop we clear the contents of the window. This is important otherwise the circle is drawn in the previous frame (previous iteration) would still be there and if we have a moving circle it’d have the effect of creating a lot of circles! So we clear the screen to erase the stuff that was drawn in the previous frame and in the fresh new screen we draw our circle shape! Note that since we didn’t set the position of the circle it’d be defaulted to (0, 0). After drawing the shape we have to display the contents of the window. Why this is important is because the shape is first drawn not on the window but on a blank empty canvas, and while SFML is drawing on this empty canvas it shows the contents of the previous iteration. And when the process of drawing on the canvas is completed, it flips the windows contents with the newly created canvas. This entire process is called double buffering if you are curious.
SFML Graphics Library | Quick Tutorial
So in this very quick tutorial, let’s learn about the basics of the mighty OpenGL-powered SFML Graphics Library.