简单的问题,我在那里搜索并没有找到一种方法来制作它。
我有一个字符串(变量一个),可以是这样的:
#FF9900Hel#FFFFFFlo
我需要一种方法让imagettftext函数识别这些颜色并使用这些颜色绘制文本。例如,在我之前提到的示例中,文本应为:红色:Hel和白色:lo。我希望我能很好地解释我的意思。
提前致谢
答案 0 :(得分:3)
您将需要解析颜色和相应的字符串,为每种独特颜色分配GD颜色资源,并单独调用imagettftext
来调整x
和y
根据需要坐标。
imagettxtext
功能不能也不会为您执行此操作。
查看imageftbbox因为您需要此函数才能计算每个文本切片的边界框,这是正确放置下一个不同颜色的文本块所必需的。
这是一个将HTML颜色转换为十六进制三元组的函数,您可以将其传递给imagecolorallocate。
function htmlColorToHex($color) {
if (substr($color, 0, 1) == '#') {
$color = substr($color, 1);
}
if (strlen($color) == 3) {
$red = str_repeat(substr($color, 0, 1), 2);
$green = str_repeat(substr($color, 1, 1), 2);
$blue = str_repeat(substr($color, 2, 1), 2);
} else {
$red = substr($color, 0, 2);
$green = substr($color, 2, 2);
$blue = substr($color, 4, 2);
}
$hex = array('r' => hexdec($red),
'g' => hexdec($green),
'b' => hexdec($blue));
return $hex;
}
您要做的最复杂的部分是正确计算每个文本部分的坐标。
答案 1 :(得分:3)
您不仅需要识别颜色,还需要对齐字符串。这不是自动的,因为它是HTML格式。
我会首先将字符串拆分为其组成部分:
// Split the text using hex colors as strings:
$hex = '[0-9a-fA-F]'; // Capital hex should be supported
$colorex = "(#{$hex}{$hex}{$hex}{$hex}{$hex}{$hex})";
// or also $colorex = "(#{$hex}{6})";
$parts = preg_split ("/{$colorex}/", $text, -1, PREG_SPLIT_DELIM_CAPTURE);
// Then you would iterate through the parts:
$color = imageColorAllocate($gd, 0, 0, 0); // Default is black
foreach($parts as $part)
{
// Scan the hex value
if (preg_match("/^{$colorex}\$/", $part, $gregs))
{
sscanf($gregs[1], "#%02x%02x%02x", &$r, &$g, &$b);
$color = imageColorAllocate($gd, $r, $g, $b);
continue;
}
// IMPROVEMENT: if count(explode("\n", $part)) > 1, $y += $height, $x = 0
// to indicate "go to next line". So this would appear on two lines:
// #012345Hel#ff7700lo,
// #443212World
// Next section will be repeated for each item
// in the exploded string.
//! $subparts = explode("\n", $part);
//! foreach($subparts as $part)
//! { // We have overwritten $part
// Here $part is printed as string at position $x, $y
// Ask GD to calculate string width
// with http://php.net/manual/en/function.imagettfbbox.php
// Calculations with $angle != 0 is a bit more difficult, entails trigonometric
// evaluation of $w and $h.
$bbox = imagettfbbox ($size, $angle, $fontfile, $part);
$w = $bbox[4] - $bbox[0]; // 0,1 is lower left corner
$h = $bbox[5] - $bbox[1]; // 4,5 is upper right
imagettftext ($gd, $size, $angle, $x, $y, $color, $fontfile, $part);
// Increment $x position by $w
$x += $w;
//! if (count($subparts) > 1)
//! {
//! $x = 0; $y += $h;
//! }
//! }
}