15.2.1 Problem
You want to draw a line, rectangle, or polygon.
You also want to be able to control if the rectangle or polygon is open or
filled in. For example, you want to be able to draw bar charts or create graphs
of stock quotes.
15.2.2 Solution
ImageLine($image, $x1, $y1, $x2, $y2, $color);
ImageRectangle($image, $x1, $y1, $x2, $y2, $color);
ImageFilledRectangle($image, $x1, $y1, $x2, $y2, $color);
$points = array($x1, $y1, $x2, $y2, $x3, $y3); ImagePolygon($image, $points, count($points)/2, $color);
$points = array($x1, $y1, $x2, $y2, $x3, $y3); ImageFilledPolygon($image, $points, count($points)/2, $color);
15.2.3 Discussion
The prototypes for all five functions
in the Solution are similar. The first parameter is the canvas to draw on. The
next set of parameters are the x and y coordinates to specify where GD should
draw the shape. In ImageLine( ), the four
coordinates are the end points of the line, and in ImageRectangle( ), they're the opposite corners of the rectangle. For
example, ImageLine($image, 0, 0, 100,
100, $color) produces a diagonal line. Passing the same
parameters to ImageRectangle( ) produces a rectangle with corners at
(0,0), (100,0), (0,100), and (100,100). Both shapes are shown in Figure 15-2.
Figure 15-2. A diagonal line and a square
The ImagePolygon( ) function
is slightly different because it can accept a variable number of vertices.
Therefore, the second parameter is an array of x and y coordinates. The function
starts at the first set of points and draws lines from vertex to vertex before
finally completing the figure by connecting back to the original point. You must
have a minimum of three vertices in your polygon (for a total of six elements in
the array). The third parameter is the number of vertices in the shape; since
that's always half of the number of elements in the array of points, a flexible
value for this is count($points) / 2 because it
allows you to update the array of vertices without breaking the call to
ImageLine().
