提问人:demooon 提问时间:8/29/2023 最后编辑:demooon 更新时间:8/30/2023 访问量:47
使用 PHP 的 GD 为同一个单词中的字母创建不同颜色的文本
using PHP's GD to create text with different colors for letters in same word
问:
我正在尝试使用 PHP 创建一个 PNG 来创建具有 2 种不同颜色的文本。如您所见,.目前我有代码来创建整个显示为白色,但我希望内部是蓝色的,而“白色”是。$text = "bluewhite";
$text
"blue"
$text
$text
white
这是更新的 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 个不同颜色的单词之间存在不同的填充,我无法弄清楚如何在单词更改时保持相同的填充。我假设这是由于每个字符的字体宽度相加,但我不确定是否有更简单的解决方案来计算每个字母的宽度,然后将其相加以计算蓝色字母之后所需的正确宽度,然后添加额外的填充以开始白色字母。
以下是我所说的例子:
有时蓝色字母后面的文字太多,有时根本没有,有时很完美。我需要它适用于所有单词,并且不知道如何获得正确的间距imagettftext()
答: 暂无答案
评论
imagettftext
imagettfbbox
imagettfbbox
imagettfbbox
解决了这个问题,非常感谢您的帮助!