In this post I will show you how to “draw” a rounded rectangle with a border. This will involve creating a new ImagickDraw object, then applying your draw settings to an Imagick object.
First, set up all your colors, image size, border width, and corner radius. After you have set all the input variables, the script will calculate the dimensions of the rectangle you are going to draw within the size of your image. To do this you must subtract the size of the border from the height and width of your desired image size, otherwise the rectangle will get cut off.
Then the script creates a new Imagick object, and applies your background color. The next step is to create your ImagickDraw object and set your fill color. If you have specified a border width greater than 0, the script will set the stroke color and width. Now the script sets up the rounded rectangle with all the settings you specified in the first step and what the script had calculated for the rectangle’s height and width.
Once the ImagickDraw object is all set up, the script will “draw” it onto the Imagick canvas previously created. And Voila! You have a rounded rectangle with a border. Uncomment the caching code if you want to have the script save the resulting image to disk.
<? $background = "transparent"; $fillcolor = "#C5E3FF"; $bordercolor = "#226FB6"; $borderwidth = 2; $cornerradius = 10; $height = 300; $width = 300; //$cachefile = 'path/to/your/cachefile.png'; //if (!file_exists($cachefile)) { try{ $rectwidth = ($borderwidth>0?($width-($borderwidth+1)):$width-1); $rectheight = ($borderwidth>0?($height-($borderwidth+1)):$height-1); $canvas = new Imagick(); $canvas->newImage($width, $height, $background, "png" ); $draw = new ImagickDraw(); $draw->setFillColor($fillcolor); if($borderwidth>0){ $draw->setStrokeColor($bordercolor); $draw->setStrokeWidth($borderwidth); } $draw->roundRectangle($borderwidth, $borderwidth, $rectheight, $rectwidth, $cornerradius, $cornerradius); $canvas->drawImage($draw); //$canvas->writeImage($cachefile); header("Content-Type: image/png"); echo $canvas; $canvas->clear(); $sanvas->destroy(); }catch(Exception $e){ echo 'Error: ', $e->getMessage(), ""; } /* }else{ $canvas = new imagick($cachefile); header("Content-Type: image/png"); echo $canvas; } */ ?> |
NOTE: “$cachefile” path must be writable by the server if you want to save the image to disk.
how to add text on a rectangle in PHP image magick