1

简单的问题,我在那里搜索并没有找到制作这个的方法。

我有一个字符串(变量),可以是这样的:

#FF9900Hel#FFFFFFlo

我需要一种方法让 imagettftext 函数识别这些颜色并使用这些颜色绘制文本。例如,在我之前提到的示例中,文本应该是:红色:Hel 和白色:lo。我希望我能很好地解释我的意思。

提前致谢

4

2 回答 2

3

您将不得不解析颜色和相应的字符串,为每种唯一颜色分配 GD 颜色资源,并根据需要单独调用imagettftext调整您的xy坐标。

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;
}

您想要做的最复杂的部分是正确计算文本每个部分的坐标。

于 2012-07-10T18:58:37.907 回答
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;
    //!     }
    //! }
}
于 2012-07-10T19:04:37.787 回答