note 43523 deleted from function.imagettfbbox by cmb
| From: | cmb@php.net | Date: | Sun, 17 Nov 2019 08:38:25 +0000 |
| Subject: | note 43523 deleted from function.imagettfbbox by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-213084@lists.php.net to get a copy of this message | ||
Note Submitter: helloktk at naver dot com
----
Here is a function which moves the center of text's bounding
box to a given pivot point (px,py) and rotates text about
that point.
<?php
$width=500;
$height=400;
$fontpath = 'c:/windows/fonts/arial.ttf';
$text = 'Finally, I have a roated text box';
$fontsize = 20;
$angle = 30.0;
// create an image and fill the background with lightgray
$image = imagecreatetruecolor($width,$height);
imagefill($image, 0, 0, 0xDDDDDD);
// bounding box
$bbox = imagettfbbox($fontsize, 0, $fontpath, $text);
// baseline point for drawing non-rotated text.
$x0= $bbox[6];
$y0=-$bbox[7];
// fixes bounding box w.r.t. image coordinate.
$bbox[5]=-$bbox[5]+$bbox[1];
$bbox[7]=-$bbox[7]+$bbox[3];
$bbox[1]=0;
$bbox[3]=0;
// get the size of image.
$sx=imagesx($image);
$sy=imagesy($image);
// center of bounding box (xc,yc);
$xc=($bbox[0]+$bbox[2])/2.0;
$yc=($bbox[1]+$bbox[7])/2.0;
// rotation angle in radian
$rad=$angle*pi()/180.0;
$sa=sin($rad);
$ca=cos($rad);
$x1=$x0-$xc;
$y1=$y0-$yc;
//pivot point(here, we take the center of image)
$px=$sx/2.0;
$py=$sy/2.0;
// new baseline point for rotated text.
$x2= intval( $x1*$ca+$y1*$sa+$px+0.5);
$y2= intval(-$x1*$sa+$y1*$ca+$py+0.5);
imagettftext($image,$fontsize,$angle,$x2,$y2,0xFF,$fontpath,$text);
// draw rotated bounding box;
rotbbox($bbox,$angle,$px,$py);
for($i=0;$i<4;$i++){
$x0=$bbox[2*$i+0];
$y0=$bbox[2*$i+1];
$j=$i+1;
if($j==4) $j=0;
$x1=$bbox[2*$j+0];
$y1=$bbox[2*$j+1];
imageline($image,$x0,$y0,$x1,$y1,0xFF0000);
}
// Show the image
imagepng($image);
function rotbbox(&$bbox,$angle,$px,$py){
$xc=($bbox[0]+$bbox[2])/2.0;
$yc=($bbox[1]+$bbox[7])/2.0;
$rad=$angle*pi()/180.0;
$sa=sin($rad);
$ca=cos($rad);
for ($i=0;$i<4;$i++){
$x=$bbox[$i*2+0]-$xc;
$y=$bbox[$i*2+1]-$yc;
$bbox[$i*2+0]= intval( $ca*$x+$sa*$y+$px+0.5);
$bbox[$i*2+1]= intval(-$sa*$x+$ca*$y+$py+0.5);
}
}
?>