-
Notifications
You must be signed in to change notification settings - Fork 30
Shapes
JSFML provides a special way to draw primitives in the form of Shapes.
There are three basic types of shapes in JSFML: rectangles, circles, and more general convex shapes. The following code sample creates some shapes with different properties and displays them in the window.
Note that this sample will place all the shapes in the top left corner of the screen. Don't worry: positioning belongs the subject of transformation and will be covered in the next chapter.
This code to draw some simple shapes will be explained in the following sections.
//... (create the window)
//Create a rectangle shape
RectangleShape rect = new RectangleShape(new Vector2f(500, 300));
//Create a red circle shape
CircleShape circle = new CircleShape(150);
circle.setFillColor(Color.RED);
//Create a regular hexagon - by making a circle approximated using only 6 points - with a thick blue outline
CircleShape hexagon = new CircleShape(75, 6);
hexagon.setOutlineColor(Color.BLUE);
hexagon.setOutlineThickness(5);
//Create a rectangular triangle with a thick blue outline
ConvexShape triangle = new ConvexShape(new Vector2f(0, 0),
new Vector2f(200, 100),
new Vector2f(0, 100));
triangle.setFillColor(Color.BLACK);
//Main loop
while (window.isOpen()) {
//Draw everything
window.clear();
window.draw(rect);
window.draw(circle);
window.draw(hexagon);
window.draw(triangle);
window.display();
// ... (handle events)
}
The most simple thing first: any Drawable object can be drawn to a RenderWindow using its [draw](http://jsfml.org/javadoc/org/jsfml/graphics/RenderWindow.html#draw(org.jsfml.graphics.Drawable\)) method. Obviously, what is drawn last will appear on top of everything else.
Advanced drawing using vertices and RenderStates will be described in a later chapter.
All Shapes provide methods to set the fill color and the properties of their outline (color and thickness). If an object should not have any fill color, Color.TRANSPARENT can be used. For no outline, the outline thickness can be set to zero.
By default, outlines have pretty ugly hard edges. To avoid this, anti-aliasing may be used if available. The ContextSettings section in the Windows chapter describes how to activate it.
A ConvexShape is made of a set of points relative to the shape's origin (the term origin will be explained in the section about transformation), represented by vectors. By convention, these points should be defined in counter-clockwise order.
Concave shapes do not belong to the standard repertoir of SFML and can not be rendered properly using ConvexShapes. A way to achieve concave shapes is splitting them into convex shapes, e.g. by Polygon triangulation, and drawing those instead.