所以我正在创建一个横幅生成器。
我将在中间添加文本,但希望它正好位于中心。
我知道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
然后将其除以二以获得使文本在图像中居中的偏移量。
// 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 文档 http://php.net/manual/en/function.imageftbbox.php
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)