PHP GD ttftext中心对齐

我正在使用 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);
?>

它使用imagettfbBox函数获取文本的宽度,然后遍历字体大小以获得正确的大小,居中并显示它.

因此,它输出以下内容

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...