PHP imagettftext()居中文字

3

我想使用以下方法使我添加到图像中的文本居中:

imagettftext($image, 85, 0, 250, 350, $color, $font, $txt );

我尝试了以下内容:

$fontwidth1 = imagefontwidth($font);
$center1 = (imagesx($image)/2) - ($fontwidth1*(strlen($txt)/2));

很不幸,它并没有工作。 imagefontwidth($font) 这一部分没有起作用 :(

有人遇到过这个问题并且知道解决方法/替代方法吗?


你能具体说明“不起作用”是什么意思吗?发生了什么事情,你期望发生什么? - Jeffrey Bosboom
(imagesx($image)/2) 的运算结果是正确的。而 ($fontwidth1*(strlen($txt)/2)) 则返回了0。 - BRDS
是的,我正确设置了所有其他变量。 - BRDS
2
我建议使用 imagettfbbox() - Austin Brunkhorst
谢谢Austing,好提示。我怎么添加这个答案呢? - BRDS
1个回答

6

imagefontwidth函数最适用于等宽字体。正如Austin Brunkhorst所说,获取居中文本的最可靠方法是使用imagettfbbox,如下所示:

$bbox = imagettfbbox(85, 0, $font, $txt);
$center1 = (imagesx($image) / 2) - (($bbox[2] - $bbox[0]) / 2);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接