所以我正在创建一个横幅生成器。
我将在中间添加文本,但希望它正好在中心。
我知道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/