PHP GD ttftext中心对齐

Mar*_*lor 6 php text gd image graph

我正在imagettftext制作一个条形图,在每个条形图顶部我想要设置.

每个条形码都有以下变量(实际上是矩形)

$x1 $y1 $x2 $y2 $imagesx $imagesy $font_size

此外,随着字符串长度的增加,fontsize应该减少.

替代文字

sha*_*mar 11

像这样做.请记住将字体文件"arial.ttf"放在当前目录中:

<?php
// Create a 650x150 image and create two colors
$im = imagecreatetruecolor(650, 150);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);

// Set the background to be white
imagefilledrectangle($im, 0, 0, 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, $font, $text, $x1, $y1, $x2, $y2, $allocatedcolor)
{
    //draw bars
    imagesetthickness($im, 2);
    imagerectangle($im, $x1, $y1, $x2, $y2, imagecolorallocate($im, 100,100,100));

    //draw text with dynamic stretching
    $maxwidth = $x2 - $x1;
    for($size = 1; true; $size+=1)
    {
        $bbox = imagettfbbox($size, 0, $font, $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, 0, $drawX, $y1 - 2, $allocatedcolor, $font, $text);
}

// Output to browser
header('Content-type: image/png');

imagepng($im);
imagedestroy($im);
?>
Run Code Online (Sandbox Code Playgroud)

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

因此,它输出以下内容:

替代文字