Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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() as ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page