【问题标题】:How to centre text in the middle of a created PNG image如何在创建的 PNG 图像中间居中文本
【发布时间】:2019-04-12 09:35:54
【问题描述】:

我已经创建了这样的图像:

$altoRouter->map('GET|POST', '/public/images/generate/[*:name]', function($string) {
    $font = 100;
    $im = imagecreatetruecolor($font * strlen($string['name']) + 50, 300);
    imagesavealpha($im, true);
    imagealphablending($im, false);
    $white = imagecolorallocatealpha($im, 255, 255, 255, 127);
    imagefill($im, 0, 0, $white);
    $black = imagecolorallocate($im, 0, 0, 0);
    imagettftext($im, $font, 0, 0, $font - 3, $black, IEZON_ROOT . "/public/uploads/NovaSquare.ttf", strtoupper($string['name']));
    header("Content-type: image/png");
    imagepng($im);
    imagedestroy($im);
});

如果我这样做/public/images/generate/example,这会给我这个输出:



但是,如您所见,文本是左对齐的,而不是在图像的中心。有什么办法可以实现吗?

【问题讨论】:

  • 查看php.net/imagettftext 上投票最多的评论(搜索“水平居中示例”)。您需要imagettfbbox 来计算文本的大小并相应地调整位置。
  • 谢谢!我会用更新的代码@ceejayoz 来回答它

标签: php image png


【解决方案1】:

感谢@ceejayoz 我使用了这个:

$altoRouter->map('GET|POST', '/public/images/generate/[*:name]', function($string) {
    $font = 100;
    $im = imagecreatetruecolor($font * strlen($string['name']) + 200, 300);
    imagesavealpha($im, true);
    imagealphablending($im, false);
    $white = imagecolorallocatealpha($im, 255, 255, 255, 127);
    imagefill($im, 0, 0, $white);
    $black = imagecolorallocate($im, 0, 0, 0);

    $width = $font * strlen($string['name']) + 200;
    $centerX = $width / 2;
    list(,,$right,,,,) = imageftbbox($font, 0, IEZON_ROOT . "/public/uploads/NovaSquare.ttf", strtoupper($string['name']));
    $left_offset = $right / 2;
    $x = $centerX - $left_offset;
    imagettftext($im, $font, 0, $x, 200, $black, IEZON_ROOT . "/public/uploads/NovaSquare.ttf", strtoupper($string['name']));
    header("Content-type: image/png");
    imagepng($im);
    imagedestroy($im);
});

现在完美居中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-11
    • 2017-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    相关资源
    最近更新 更多