Creating a Gradient


The GD graphics package doesn't come with functions to draw graphics gradients that will let you create shaded figures; however, you can do the job yourself. For example, say that you want a sphere that looks three-dimensional. You can create that yourself with a little bit of workin this case, by drawing successive filled circles of different colors to make it appear shaded.

First, we'll create a for loop that loops over every radius needed to create the figure, pixel-by-pixel. Then we'll create a new color for each iteration through the loop, getting brighter toward the center:

 $image_width = 200; for ($loop_index = 0; $loop_index <= $image_width / 2; $loop_index++) {     $current_color = imagecolorallocate($image, 2 * 255 * $loop_index /         $image_width, 2 * 255 * $loop_index / $image_width, 0);         .         .         . } 

When you have your drawing color, draw a filled ellipse with imagefilledellipse like this:

 $image_width = 200; for ($loop_index = 0; $loop_index <= $image_width / 2; $loop_index++) {     $current_color = imagecolorallocate($image, 2 * 255 * $loop_index /         $image_width, 2 * 255 * $loop_index / $image_width, 0);     imagefilledellipse($image, $image_width / 2, $image_width / 2,         $image_width - 2 * $loop_index, $image_width - 2 * $loop_index,         $current_color); } 

All the code appears in phpgradient.php, Example 16, where we're creating the 3D sphere in a JPEG image.

Example 16. Drawing a gradient, phpgradient.php
 <?php     $image_width = 200;     $image = imagecreate($image_width, $image_width);     $back_color = imagecolorallocate($image, 255, 255, 255);     for ($loop_index = 0; $loop_index <= $image_width / 2; $loop_index++)     {         $current_color = imagecolorallocate($image, 2 * 255 * $loop_index /             $image_width, 2 * 255 * $loop_index / $image_width, 0);         imagefilledellipse($image, $image_width / 2, $image_width / 2,             $image_width - 2 * $loop_index, $image_width - 2 * $loop_index,             $current_color);     }     header('Content-Type: image/jpeg');     imagejpeg($image);     imagedestroy($image); ?> 

You can see the results in Figure 17, where the sphere does indeed have a 3D appearance. Very cool.

Figure 17. Drawing a gradient.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net