微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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函数获取文本的宽度,然后遍历字体大小以获得正确的大小,居中并显示它.

因此,它输出以下内容

原文地址:https://www.jb51.cc/php/133295.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐