Drawing a Polygon


If you want to draw your own figures, you can trace them together using multiple lines, but there's an easier wayyou can use the imagepolygon function to draw a polygon simply by passing it an array of points. Here's how you use this function in general:

 imagepolygon(resource image, array points, int num_points, int color) 

This function creates a polygon in image. The points array is a PHP array containing the polygon's vertices (points[0] = x0, points[1] = y0, points[2] = x1, points[3] = y1, and so on). The num_points value holds the total number of points in the polygon, and color is the drawing color you want to use.

For example, here's an array of points, $points, in which every pair of values (array[0] and array[1], array[2] and array[3], and so on) specifies a point on the screen:

 $points = array(     0  => 120, 1  => 60,     2  => 130, 3  => 60,     4  => 160, 5  => 80,     6  => 180, 7  => 20,     8  => 150, 9  => 40,     10 => 110, 11 => 10,     12 => 110, 13 => 80 ); 

Now we can draw the resulting polygon with imagepolygon:

 imagepolygon($image, $points, 7, $draw_color ); 

The whole example appears in phppolygon.php, Example 6.

Example 6. Drawing polygons, phppolygon.php
 <?php     $points = array(         0  => 120, 1  => 60,         2  => 130, 3  => 60,         4  => 160, 5  => 80,         6  => 180, 7  => 20,         8  => 150, 9  => 40,         10 => 110, 11 => 10,         12 => 110, 13 => 80     );     $image_height = 100;     $image_width = 300;     $image = imagecreate($image_width, $image_height);     $back_color = imagecolorallocate($image, 200, 200, 200);     $draw_color = imagecolorallocate($image, 0, 0, 0);     imagepolygon($image, $points, 7, $draw_color );     header('Content-type: image/jpeg');     imagejpeg($image);     imagedestroy($image); ?> 

We'll use an HTML document, phppolygon.html, to host the new image:

 <HTML>     <HEAD>         <TITLE>Drawing polygons</TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Drawing polygons             </H1>             <BR>             <IMG src="/books/1/265/1/html/2/phppolygon.php">         </CENTER>     </BODY> </HTML> 

The new polygon appears in Figure 7. Very nice.

Figure 7. Drawing a polygon.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net