Page 107 - Programming Microcontrollers in C
P. 107
92 Chapter 2 Advanced C Topics
draw_rectangle(window);
draw_circle(cir);
return 0;
}
At the beginning of the program, several important struct types
are defined.These include a point, a rectangle, a circle, and a func
tion to make circle given its center and its radius. Two macro
definitions are needed. The first is the calculation for the minimum
value of a and b and the second returns the absolute value of the
argument. Two function prototypes are included. These functions
will draw a rectangle and a circle to the screen, respectively.
Inside the main program cir is declared to be of the type
struct circle, center is struct point , and window is
of the type struct rect. When window is defined, it is initial
ized to the values shown. This type of initialization is acceptable to
structures as well as arrays. The rectangle is defined by two points.
The point {80,80} is the lower lefthand corner of the rectangle, and
the point {600,400} is the upper right corner. These locations are
implementation dependent, and in some cases might represent the
upper left corner {80,80} and the lower right corner {600,400}.
The center of the window is calculated by determining the aver
age value of the x members of each point along with the average
value of the y members. These values are the exact center of the
rectangle. The center of the inscribed circle will lie at this point. The
radius of the inscribed circle will be one-half the length of the short
est dimension of the rectangle. The two potential value are calculated
as xc and yc. Here the absolute value is used, because in general, it
is impossible to know that the rectangle will be specified by the lower
left hand corner in p1 and the upper right hand corner in p2. If these
points were interchanged, negative values would be calculated. The
selection of the positive result through the abs() macro avoids
this problem. The final choice for radius is the minimum value of
xc or yc.
The above calculations provide enough information to specify the
circle, so cir is calculated as the return value from make_circle().
Finally, two compiler specific functions, draw_rectangle() and
draw_circle(), are used to draw the calculated figures to the screen.