php - 使用 PHP GD 在图像上居中文本

标签 php gd php-gd

所以我正在创建一个横幅生成器。

我将在中间添加文本,但希望它正好在中心。
我知道imagettftext可用于在横幅上写字,但不会使其居中。

一个可能的解决方案可能是找到文本的宽度,然后使用从横幅宽度的一半中取出的一半,但我不知道如何做到这一点。

我正在使用 PHP-GD,不想使用我必须安装的任何其他东西。

imagettftext($img, 14, 0, (468 - ((strlen($_GET['description']) * imagefontwidth(imageloadfont('minecraft.ttf'))) / 1)), 85, imagecolorallocate($img, 0, 0, 0), 'minecraft.ttf', $_GET['description']);

上面的代码正在生成上面的结果。小字符串很好,但一定有问题,因为一旦它们变长,它就会失败。

最佳答案

您可以通过从 imageftbbox 获取外部边界的宽度来使文本居中。然后将其除以 2 以获得将图像中的文本居中的偏移量。

// Get image dimensions
  $width = imagesx($image);
  $height = imagesy($image);
// Get center coordinates of image
  $centerX = $width / 2;
  $centerY = $height / 2;
// Get size of text
  list($left, $bottom, $right, , , $top) = imageftbbox($font_size, $angle, $font, $text);
// Determine offset of text
  $left_offset = ($right - $left) / 2;
  $top_offset = ($bottom - $top) / 2;
// Generate coordinates
  $x = $centerX - $left_offset;
  $y = $centerY + $top_offset;
// Add text to image
  imagettftext($image, $font_size, $angle, $x, $y, $color, $font, $text);
imageftbbox documentation

关于php - 使用 PHP GD 在图像上居中文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22920945/

相关文章:

php - 仅当字符串不为空/空时如何解密字符串

php - 在这个图像像素循环中我做错了什么?

php - 您可以将使用 imagecopyresized() 的图像保存到 MySQL 吗?

php - Ajax 并返回由 PHP GD 创建的图像

php - 为什么修复 GD 的 png 透明度问题的解决方案不起作用?

php - 如何更改 WordPress 中帖子的日期

php - 使用两个嵌套的 WHERE 子句可以吗?

php - Mysql查询语法失败

PHP GD ttftext 居中对齐

php - 将 PNG 保存到变量