bool imagefilledrectangle ( resource image, int x1, int y1, int x2, int y2, int color)
The imagefilledrectangle() function takes six parameters in total, which are, in order: an image resource to draw on, the top-left X coordinate, the top-left Y coordinate, the bottom-right X coordinate, the bottom-right Y coordinate, and a colour to use. Note that there is a similar function called imagerectangle(), which takes exactly the same parameters with the difference being that it only draws the outline of the rectangle, whereas imagefilledrectangle() fills the shape in with colour.
In order to draw a rectangle in such a way as to make it stand out, we need to allocate another colour, then draw the rectangle. Here is how that is done:
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 10, 10, 390, 290, $white);
Put those two lines just after the definition of $gold, then save the modified script and refresh phppicture.html. Not surprisingly, we now have a rectangle in there.
In case you are getting bored with simple stuff, let's take a leap forward with imagefilledrectangle() and draw a pattern using a loop. Take a copy of picture1.php and call it picture2.php - be sure to modify your HTML so that the image SRC points to picture2.php.
Bring up picture2.php in your favourite editor, and modify it to this:
<?php
$image = imagecreate(400,300);
$gold = imagecolorallocate($image, 255, 240, 00);
$white = imagecolorallocate($image, 255, 255, 255);
$colour = $white;
for ($i = 400, $j = 300; $i > 0; $i -= 4, $j -= 3) {
if ($colour == $white) {
$colour = $gold;
} else {
$colour = $white;
}
imagefilledrectangle($image, 400 - $i, 300 - $j, $i, $j, $colour);
}
imagepng($image);
imagedestroy($image);
?>
The code is pretty much the same as before, with the addition of a simple for loop. Note that our loop sets the starting value for $i and $j, and also decrements $i and $j with each iteration.
As you can see in the code, we call imagefilledrectangle() each iteration of the loop, slowly making the rectangle smaller and smaller as $i and $j decrease in value. Save the script, and see how it looks in your web browser.
Author's Note: In place of a plain colour, it is possible to fill your shapes with a tiled image using the imagesettile() function.
Want to learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: More shapes >>
Previous chapter: Choosing a format
Jump to:
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.