Points and Lines
Drawing points
is accomplished with the function imagesetpixel()
, which takes four parameters: the image to draw on, the X and Y coordinates, and the color to use. Thus, you can use it like this:
$width = 255; $height = 255; $image = imagecreatetruecolor($width, $height); for ($i = 0; $i <= $width; ++$i) { for ($j = 0; $j <= $height; ++$j) { $col = imagecolorallocate($image, 255, $i, $j); imagesetpixel($image, $i, $j, $col); } } header("Content-type: image/png"); imagepng($image); imagedestroy($image);
In that example, there are two loops to handle setting the green and blue parameters with imagecolorallocate()
, with red always being set to 255. This color is then used to set the relevant pixel to the newly allocated color, which should give you a smooth gradient like the one in Figure 16-23.
Figure 16-23. Smooth gradiants using per-pixel coloring
Drawing lines is only a little more difficult than individual pixels, and is handled by the imageline()
function. This time, the parameters are the image to draw on, the X and Y coordinates of the start of the line, the X and Y coordinates of the end of the line, and the color to use for drawing. We can extend our pixel script to draw a grid over the gradient by looping from 0 to $width
and $height
, incrementing by 15 each time, and drawing a line at the appropriate place. $width
and $height
were both set to 241 in the previous ...
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.