在 PHP 中使用多种字体编写文本

write a text with multiple fonts in PHP

我目前正在使用 Intervention class 在图片上写文字。

使用text()方法很容易写:

$img->text('The quick brown fox jumps over the lazy dog.', 120, 100);

Documentation

但我的问题是我想要一个单词的每个字符具有不同的字体。例如,假设单词 test,每个字符必须使用不同的字体。这不容易实现,因为我找不到开始下一个字符的位置,例如在单词 test 中,当我写 t 然后当我想调用 text()e的方法,我不知道应该把位置放在哪里,所以字符e就在t之后。

我如何 得到最后一个字符的 position 以便我可以在最后一个字符结束的地方开始写下一个字符?还是有其他方法可以做到这一点?

这是我用来获取字符串宽度的方法。
我使用 imagettftext(),所以它可能不适合你。但是这段代码有效。
因此,如果您必须在什么都没有和有效代码之间做出选择...

$type_space = imagettfbbox($size, 0, $font, $text); // 0 = angle
$text_width = abs($type_space[4] - $type_space[6]);

imagettfbbox returns 值数组。
http://php.net/manual/en/function.imagettfbbox.php

Imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text:
0 lower left corner, X position
1 lower left corner, Y position
2 lower right corner, X position
3 lower right corner, Y position
4 upper right corner, X position
5 upper right corner, Y position
6 upper left corner, X position
7 upper left corner, Y position

代码采用右上角 x - 左上角 x,这应该表示宽度。