[ Team LiB ] Previous Section Next Section

Drawing a Polygon

You can draw more sophisticated shapes using imagepolygon(). This function requires an image resource, an array of point coordinates, an integer representing the number of points in the shape, and a color resource. The array passed to imagepolygon() should be numerically indexed. The first two elements give the coordinates of the first point, the second two give the coordinates of the second point, and so on. imagepolygon() fills in the lines between the points, automatically closing your shape by joining the final point to the first. You can create a filled polygon with the imagefilledpolygon() function.

Listing 15.6 draws a filled polygon, outputting the result to the browser.

Listing 15.6 Drawing a Polygon with imagefilledpolygon()
 1: <?php
 2: header("Content-type: image/png");
 3: $image = imagecreate( 200, 200 );
 4: $red = imagecolorallocate($image, 255,0,0);
 5: $blue = imagecolorallocate($image, 0,0,255 );
 6: $points = array (   10, 10,
 7:       190, 190,
 8:       190, 10,
 9:       10, 190
10:       );
11: imagefilledpolygon( $image, $points, count( $points )/2 , $blue );
12: imagepng($image);
13: ?>

After acquiring image and color resources (lines 25), we create an array of coordinates on line 6. Notice that when we call imagefilledpolygon() on line 11, we tell it the number of points we want to connect by counting the number of elements in the $points array and dividing the result by 2. Figure 15.6 shows the output from Listing 15.6.

Figure 15.6. Drawing a polygon with imagefilled polygon().


    [ Team LiB ] Previous Section Next Section