Book HomePHP CookbookSearch this book

15.4. Drawing with Patterned Lines

15.4.1. Problem

You want to draw shapes using line styles other than the default, a solid line.

15.4.2. Solution

To draw shapes with a patterned line, use ImageSetStyle( ) and pass in IMG_COLOR_STYLED as the image color:

$black = ImageColorAllocate($image,   0,   0,   0);
$white = ImageColorAllocate($image, 255, 255, 255);

// make a two-pixel thick black and white dashed line
$style = array($black, $black, $white, $white);
ImageSetStyle($image, $style);

ImageLine($image, 0, 0, 50, 50, IMG_COLOR_STYLED);
ImageFilledRectangle($image, 50, 50, 100, 100, IMG_COLOR_STYLED);

15.4.3. Discussion

The line pattern is defined by an array of colors. Each element in the array is another pixel in the brush. It's often useful to repeat the same color in successive elements, as this increases the size of the stripes in the pattern.

For instance, here is code for a square drawn with alternating white and black pixels, as shown in left side of Figure 15-4:

$style = array($white, $black);
ImageSetStyle($image, $style);
ImageFilledRectangle($image, 0, 0, 49, 49, IMG_COLOR_STYLED);

This is the same square, but drawn with a style of five white pixels followed by five black ones, as shown in the middle of Figure 15-4:

$style = array($white, $white, $white, $white, $white, 
               $black, $black, $black, $black, $black);
ImageSetStyle($image, $style);
ImageFilledRectangle($image, 0, 0, 49, 49, IMG_COLOR_STYLED);
Figure 15-4

Figure 15-4. Three squares with alternating white and black pixels

The patterns look completely different, even though both styles are just white and black pixels.

If the brush doesn't fit an integer number of times in the shape, it wraps around. In the previous examples, the square is 50 pixels wide. Since the first brush is 2 pixels long, it fits exactly 25 times; the second brush is 10 pixels, so it fits 5 times. But, if you make the square 45 by 45 and used the second brush, you don't get straight lines as you did previously, as shown in the right side of Figure 15-4:

ImageFilledRectangle($image, 0, 0, 44, 44, IMG_COLOR_STYLED);

15.4.4. See Also

Recipe 15.2 and Recipe 15.3 for more on drawing shapes; documentation on ImageSetStyle( ) at http://www.php.net/imagesetstyle.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.