Friday, January 8, 2010

Recipe 17.3. Drawing with Patterned Lines










Recipe 17.3. Drawing with Patterned Lines



17.3.2. Problem


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




17.3.3. 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);





17.3.4. 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 the left side of Figure 17-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 17-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);




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 use the second brush, you don't get straight lines as you did previously, as shown in the right side of Figure 17-4:


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





17.3.5. See Also


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













No comments: