我正在使用
imagettftext
来制作条形图,并且在每个条形图的顶部我想要设置值.
每个条形码都有以下变量(实际上是矩形)
$X1
$Y1
$X2
$Y2
$imagesx
$imagesy
$FONT_SIZE
此外,随着字符串长度的增加,fontsize应该减少.
像这样做.请记住将字体文件“arial.ttf”放在当前目录中:
<?PHP // Create a 650x150 image and create two colors $im = imagecreatetruecolor(650,150); $white = imagecolorallocate($im,255,255); $black = imagecolorallocate($im,0); // Set the background to be white imagefilledrectangle($im,649,149,$white); // Path to our font file $font = './arial.ttf'; //test it out for($i=2;$i<10;$i++) WriteTextForMe($im,$font,str_repeat($i,$i),-140 + ($i*80),70 + rand(-30,30),-160 + (($i+1)*80),150,$black); //this function does the magic function WriteTextForMe($im,$text,$x1,$y1,$x2,$y2,$allocatedcolor) { //draw bars imagesetthickness($im,2); imagerectangle($im,imagecolorallocate($im,100,100)); //draw text with dynamic stretching $maxwidth = $x2 - $x1; for($size = 1; true; $size+=1) { $bBox = imagettfbBox($size,$text); $width = $bBox[2] - $bBox[0]; if($width - $maxwidth > 0) { $drawsize = $size - 1; $drawX = $x1 + $lastdifference / 2; break; } $lastdifference = $maxwidth - $width; } $size--; imagettftext($im,$drawsize,$drawX,$y1 - 2,$allocatedcolor,$text); } // Output to browser header('Content-type: image/png'); imagepng($im); imagedestroy($im); ?>