10.7 Using Shape primitives
In this section, we will walk you through some of the primitive facilities of our graphics library: Simple_window, Window, Shape, Text, Polygon, Line, Lines, Rectangle, Color, Line_style, Point, Axis. The aim is to give you a broad view of what you can do with those facilities, but not yet a detailed understanding of any of those classes. In the next chapters, we explore the design of each.
We will now walk through a simple program, explaining the code line by line and showing the effect of each on the screen. When you run the program, you’ll see how the image changes as we add shapes to the window and modify existing shapes. Basically, we are “animating” the progress through the code by looking at the program as it is executed.
10.7.1 Axis
An almost blank window isn’t very interesting, so we’d better add some information. What would we like to display? Just to remind you that graphics is not all fun and games, we will start with something serious and somewhat complicated, an axis. A graph without axes is usually a disgrace. You just don’t know what the data represents without axes. Maybe you explained it all in some accompanying text, but it is far safer to add axes; people often don’t read the explanation and often a nice graphical representation gets separated from its original context. So, a graph needs axes:
Axis xa {Axis::x, Point{20,300}, 280, 10, "x axis"}; // make an Axis // an Axis is a kind of Shape // Axis::x means horizontal // starting at (20,300) // 280 pixels long // with 10 "notches" // label the axis "x axis" win.attach(xa); // attach xa to the window, win win.set_label("X axis"); // re-label the window win.wait_for_button(); // display!
The sequence of actions is: make the axis object, add it to the window, and finally display it:
We can see that an Axis::x is a horizontal line. We see the required number of “notches” (10) and the label “x axis.” Usually, the label will explain what the axis and the notches represent. Naturally, we chose to place the x axis somewhere near the bottom of the window. In real life, we’d represent the height and width by symbolic constants so that we could refer to “just above the bottom” as something like y_max−bottom_margin rather than by a “magic constant,” such as 300 (§3.3.1, §13.6.3).
To help identify our output we relabeled the screen to X axis using Window’s member function set_label().
Now, let’s add a y axis:
Axis ya {Axis::y, Point{20,300}, 280, 10, "y axis"}; ya.set_color(Color::cyan); // choose a color for the y axis ya.label.set_color(Color::dark_red); // choose a color for the text win.attach(ya); win.set_label("Y axis"); win.wait_for_button(); // display!
Just to show off some facilities, we colored our y axis cyan and our label dark red.
We don’t actually think that it is a good idea to use different colors for x and y axes. We just wanted to show you how you can set the color of a shape and of individual elements of a shape. Using lots of color is not necessarily a good idea. In particular, novices often use color with more enthusiasm than taste.
10.7.2 Graphing a function
What next? We now have a window with axes, so it seems a good idea to graph a function. We make a shape representing a sine function and attach it:
double dsin(double d) { return sin(d); } // chose the right sin() (§13.3) Function sine {dsin,0,100,Point{20,150},1000,50,50}; // sine curve // plot sin() in the range [0:100) with (0,0) at (20,150) // using 1000 points; scale x values *50, scale y values *50 win.attach(sine); win.set_label("Sine"); win.wait_for_button();
Here, the Function named sine will draw a sine curve using the standard-library function sin(double) to generate values. We explain details about how to graph functions in §13.3. For now, just note that to graph a function we have to say where it starts (a Point) and for what set of input values we want to see it (a range), and we need to give some information about how to squeeze that information into our window (scaling):
Note how the curve simply stops when it hits the edge of the window. Points drawn outside our window rectangle are simply ignored by the GUI system and never seen.
10.7.3 Polygons
A graphed function is an example of data presentation. We’ll see much more of that in Chapter 11. However, we can also draw different kinds of objects in a window: geometric shapes. We use geometric shapes for graphical illustrations, to indicate user interaction elements (such as buttons), and generally to make our presentations more interesting. A Polygon is characterized by a sequence of points, which the Polygon class connects by lines. The first line connects the first point to the second, the second line connects the second point to the third, and the last line connects the last point to the first:
sine.set_color(Color::blue); // we changed our mind about sine’s color Polygon poly; // a polygon; a Polygon is a kind of Shape poly.add(Point{300,200}); // three points make a triangle poly.add(Point{350,100}); poly.add(Point{400,200}); poly.set_color(Color::red); win.attach(poly); win.set_label("Triangle"); win.wait_for_button();
This time we change the color of the sine curve (sine) just to show how. Then, we add a triangle, just as in our first example from §10.3, as an example of a polygon. Again, we set a color, and finally, we set a style. The lines of a Polygon have a “style.” By default, that is solid, but we can also make those lines dashed, dotted, etc. as needed (§11.5). We get
10.7.4 Rectangles
CC
A screen is a rectangle, a window is a rectangle, and a piece of paper is a rectangle. In fact, an awful lot of the shapes in our modern world are rectangles (or at least rectangles with rounded corners). There is a reason for this: a rectangle is the simplest shape to deal with. For example, it’s easy to describe (top left corner plus width plus height, or top left corner plus bottom right corner, or whatever), it’s easy to tell whether a point is inside a rectangle or outside it, and it’s easy to get hardware to draw a rectangle of pixels fast.
So, most higher-level graphics libraries deal better with rectangles than with other closed shapes. Consequently, we provide Rectangle as a class separate from the Polygon class. A Rectangle is characterized by its top left corner plus a width and height:
Rectangle r {Point{200,200}, 100, 50}; // top left corner, width, height win.attach(r); win.set_label("Rectangle"); win.wait_for_button();
From that, we get
Please note that making a polyline with four points in the right places is not enough to make a Rectangle. It is easy to make a Closed_polyline that looks like a Rectangle on the screen (you can even make an Open_polyline that looks just like a Rectangle). For example:
Closed_polyline poly_rect; poly_rect.add(Point{100,50}); poly_rect.add(Point{200,50}); poly_rect.add(Point{200,100}); poly_rect.add(Point{100,100}); win.set_label("Polyline"); win.attach(poly_rect); win.wait_for_button();
That polygon looks exactly – to the last pixel – like a rectangle:
However, it only looks like a Rectangle. No Rectangle has four points:
poly_rect.add(Point{50,75}); win.set_label("Polyline 2"); win.wait_for_button();
No rectangle has five points:
CC
In fact, the image on the screen of the 4-point poly_rect is a rectangle. However, the poly_rect object in memory is not a Rectangle and it does not “know” anything about rectangles.
It is important for our reasoning about our code that a Rectangle doesn’t just happen to look like a rectangle on the screen; it maintains the fundamental guarantees of a rectangle (as we know them from geometry). We write code that depends on a Rectangle really being a rectangle on the screen and staying that way.
10.7.5 Fill
We have been drawing our shapes as outlines. We can also “fill” a rectangle with color:
r.set_fill_color(Color::yellow); // color the inside of the rectangle poly.set_style(Line_style(Line_style::dash,4)); poly_rect.set_style(Line_style(Line_style::dash,2)); poly_rect.set_fill_color(Color::green); win.set_label("Fill"); win.wait_for_button();
We also decided that we didn’t like the line style of our triangle (poly), so we set its line style to “fat (thickness four times normal) dashed.” Similarly, we changed the style of poly_rect (now no longer looking like a rectangle) and filled it with green:
If you look carefully at poly_rect, you’ll see that the outline is printed on top of the fill.
It is possible to fill any closed shape (§11.7, §11.7.2). Rectangles are just special in how easy (and fast) they are to fill.
10.7.6 Text
CC
Finally, no system for drawing is complete without a simple way of writing text – drawing each character as a set of lines just doesn’t cut it. We label the window itself, and axes can have labels, but we can also place text anywhere using a Text object:
Text t {Point{150,150}, "Hello, graphical world!"}; win.attach(t); win.set_label("Text"); win.wait_for_button();
From the primitive graphics elements you see in this window, you can build displays of just about any complexity and subtlety. For now, just note a peculiarity of the code in this chapter: there are no loops, no selection statements, and all data was “hardwired” in. The output was just composed of primitives in the simplest possible way. Once we start composing these primitives, using data and algorithms, things will start to get interesting.
We have seen how we can control the color of text: the label of an Axis (§10.7.1) is simply a Text object. In addition, we can choose a font and set the size of the characters:
t.set_font(Font::times_bold); t.set_font_size(20); win.set_label("Bold text"); win.wait_for_button();
We enlarged the characters of the Text string Hello, graphical world! to point size 20 and chose the Times font in bold:
10.7.7 Images
We can also load images from files:
This was done by:
Image copter {Point{100,50},"mars_copter.jpg"}; win.attach(copter); win.set_label("Mars copter"); win.wait_for_button();
That photo is relatively large, and we placed it right on top of our text and shapes. So, to clean up our window a bit, let us move it a bit out of the way:
copter.move(100,250); win.set_label("Move"); win.wait_for_button();
Note how the parts of the photo that didn’t fit in the window are simply not represented. What would have appeared outside the window is “clipped” away.
10.7.8 And much more
And here, without further comment, is some more code:
Circle c {Point{100,200},50}; Ellipse e {Point{100,200}, 75,25}; e.set_color(Color::dark_red); Mark m {Point{100,200},'x'}; m.set_color(Color::red); ostringstream oss; oss << "screen size: " << x_max() << "*" << y_max() << "; window size: " << win.x_max() << "*" << win.y_max(); Text sizes {Point{100,20},oss.str()}; Image scan{ Point{275,225},"scandinavia.jfif" }; scan.scale(150,200); win.attach(c); win.attach(m); win.attach(e); win.attach(sizes); win.attach(scan); win.set_label("Final!"); win.wait_for_button();
Can you guess what this code does? Is it obvious?
AA
The connection between the code and what appears on the screen is direct. If you don’t yet see how that code caused that output, it soon will become clear.
Note the way we used an ostringstream (§9.11) to format the text object displaying sizes. The string composed in oss is referred to as oss.str().