使用 PHP 的 GD 为同一个单词中的字母创建不同颜色的文本

using PHP's GD to create text with different colors for letters in same word

提问人:demooon 提问时间:8/29/2023 最后编辑:demooon 更新时间:8/30/2023 访问量:47

问:

我正在尝试使用 PHP 创建一个 PNG 来创建具有 2 种不同颜色的文本。如您所见,.目前我有代码来创建整个显示为白色,但我希望内部是蓝色的,而“白色”是。$text = "bluewhite";$text"blue"$text$textwhite

这是更新的 php 代码,用于从 中创建白色文本。$text

$text = strtoupper('bluewhite');
$font = 'font.ttf';

$im = imagecreatetruecolor(1200, 2100);

imagealphablending($im, true);
imagesavealpha($im, true);

$black = imagecolorallocate($im, 255, 255, 255);
$blue = imagecolorallocate($im, 66, 139, 200);

$bluetext = imagettftext($im, 100, 0, 0, 120, $blue, $font, substr($text, 0, 4));

imagettftext($im, 100, 0, 321, 120, -$black, $font, substr($text, 4));

$crop = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => 900, 'height' => 140]);

imagealphablending($crop, false);
imagesavealpha($crop, false);

$clear = imagecolorallocate($crop, 0, 0, 0);
imagecolortransparent($crop, $clear);

header('Content-Type: image/png');
imagepng($crop, null, 9);
imagedestroy($crop);

编辑:我即将实现上述前 4 个字母为蓝色,其余字母为白色,但我现在的新问题是 2 个不同颜色的单词之间存在不同的填充,我无法弄清楚如何在单词更改时保持相同的填充。我假设这是由于每个字符的字体宽度相加,但我不确定是否有更简单的解决方案来计算每个字母的宽度,然后将其相加以计算蓝色字母之后所需的正确宽度,然后添加额外的填充以开始白色字母。

以下是我所说的例子:

As you can see there is too much space after the blue text, where the white text starts

and for some words, the spacing between the blue and white letters are perfect, which is what I'm trying to achieve every time

for some words there is no spacing at all

有时蓝色字母后面的文字太多,有时根本没有,有时很完美。我需要它适用于所有单词,并且不知道如何获得正确的间距imagettftext()

php 图像 文本 颜色 gd

评论

1赞 CBroe 8/29/2023
“我相信必须有一种本土的方法来实现这一目标。- 当然 - 调用两次,文本的每个部分一次,颜色不同。当然,您必须计算第二部分的正确位置才能开始。 可用于“测量”文本的尺寸。imagettftextimagettfbbox
0赞 demooon 8/30/2023
我设法实现了这一点,但遇到了一个新问题。我编辑了我的原始帖子,希望能找到解决方案。
0赞 CBroe 8/30/2023
显示您现在实际使用的代码。“但我不确定是否有更简单的解决方案,即计算每个字母的宽度以将其相加以计算蓝色字母后所需的正确间距”——您是否按照我的建议使用了?imagettfbbox
0赞 demooon 8/30/2023
imagettfbbox解决了这个问题,非常感谢您的帮助!

答: 暂无答案