代码之家  ›  专栏  ›  技术社区  ›  Mark Lalor

PHP GD ttftext中心对齐

  •  6
  • Mark Lalor  · 技术社区  · 14 年前

    我在用 imagettftext 制造 而在 每个吧台的顶部 价值 .

    我有 每个条形图的以下变量 (实际上是矩形)

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

    fontsize应该随着字符串长度的增加而减小。

    alt text

    2 回复  |  直到 14 年前
        1
  •  11
  •   shamittomar    14 年前

    像这样做。记住放置字体文件“宋体.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);
    ?>
    

    它使用 imagettfbbox 函数获取文本的宽度,然后在字体大小上循环以获得正确的大小,将其居中并显示。

    alt text

        2
  •  2
  •   jwueller    14 年前

    您可以使用PHP的 imagettfbbox -function :

    // define text and font
    $text = 'some bar label';
    $font = 'path/to/some/font.ttf';
    
    // calculate text size (this needs to be adjusted to suit your needs)
    $size = 10 / (strlen($text) * 0.1);
    
    // calculate bar center
    $barCenter = $x1 + ($x2 - $x1) / 2;
    
    // calculate text position (centered)
    $bbox = imagettfbbox($size, 0, $font, $text);
    $textWidth = $bbox[2] - $bbox[0];
    $positionX = $textWidth / 2 + $barCenter;
    $positionY = $y1 - $size;
    

    编辑: 更新了代码为你做所有的工作。