Complex Shapes

Rectangles, ellipses, and arcs are inherently easy to use because they have predefined shapes, whereas polygons are multisided shapes of arbitrary geometry and are more complicated to define.

The parameter list is straightforward and the same for both imagefilledpolygon() and imagepolygon(): the image resource to draw on, an array of points to draw, the number of total points, and the color. The array is made up of pairs of X,Y pixel positions. PHP uses these coordinates sequentially, drawing lines from the first (X,Y) to the second, to the third, etc., until drawing a line back from the last one to the first.

The easiest thing to draw is a square, and we can emulate the functionality of imagefilledrectangle() like this:

    $points = array(
            20, // x1, top-left
            20, // y1

            230, // x2, top-right
            20, // y2

            230, // x3, bottom-right
            230, // y3

            20, // x4, bottom-left
            230 // y4
    );

    $image = imagecreatetruecolor(250, 250);
    $green = imagecolorallocate($image, 0, 255, 0);
    imagefilledpolygon($image, $points, 4, $green );

    header('Content-type: image/png');
    imagepng($image);
    imagedestroy($image);

I have added extra whitespace in there to make it quite clear how the points work in the $points array—see Figure 16-5 for how this code looks in action. For more advanced polygons, try writing a function that generates the points for you.

A square drawn using imagefilledpolygon() as opposed to imagefilled-rectangle()—as long as you get the numbers right, it should look exactly the same

Figure 16-5. A square drawn using imagefilledpolygon() ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.