PHP GD ttftext中心对齐
发布时间:2020-12-13 22:41:02 所属栏目:PHP教程 来源:网络整理
导读:我正在使用 imagettftext 来制作条形图,并且在每个条形图的顶部我想要设置值. 每个条形码都有以下变量(实际上是矩形) $X1 $Y1 $X2 $Y2 $imagesx $imagesy $FONT_SIZE 此外,随着字符串长度的增加,fontsize应该减少. 像这样做.请记住将字体文件“arial.ttf”放
我正在使用
imagettftext 来制作条形图,并且在每个条形图的顶部我想要设置值.
每个条形码都有以下变量(实际上是矩形) $X1 此外,随着字符串长度的增加,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); ?> 它使用imagettfbbox函数来获取文本的宽度,然后遍历字体大小以获得正确的大小,居中并显示它. 因此,它输出以下内容: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |