【问题标题】:PHP GD ttftext center alignmentPHP GD ttftext 居中对齐
【发布时间】:2011-04-10 09:22:59
【问题描述】:

我正在使用imagettftext 制作条形图,并在每个条形的顶部我想放置

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

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

另外,字体大小应该随着字符串长度的增加而减小。

【问题讨论】:

  • 小子,你有事要做!它必须是PHP吗?那里有这么好的(和现成的)javascript绘图库......
  • 我正在制作一个 PHP 库,所以...
  • 如果有示例的“制作条形图”代码会很好,你可以发布它吗?

标签: php image text graph gd


【解决方案1】:

您可以使用 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;

编辑:更新了代码,为您完成所有工作。

【讨论】:

  • 您将如何确切地使用它来获得编写它的位置,使其居中
  • 我相应地编辑了我的帖子。代码计算给定文本的 x 轴位置,居中对齐$positionX
  • 嗯,让我重新写下问题
  • 嗯,这是一个不完整的答案,但您不能指望人们为您完成所有工作。 imagettfbbox 是您肯定需要的工具,因为它会为您提供文本的投影尺寸。您可以使用它来使文​​本相对于每个条居中。
  • $positionX = $textWidth / 2 + $barCenter; 应该是$positionX = $barCenter - $textWidth / 2 ;
【解决方案2】:

这样做。记得把字体文件“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);
?>

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

因此,它会输出以下内容:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    • 2021-06-01
    • 2011-03-13
    • 2016-08-17
    • 2011-11-29
    • 2013-02-22
    相关资源
    最近更新 更多