【发布时间】:2011-04-02 16:36:06
【问题描述】:
我正在获取 xml 提要并从文本中创建图像。我想做的是将链接文本着色为与常规文本不同的颜色。我正在遍历文本以查找链接,但无法弄清楚如何为该文本着色。
【问题讨论】:
我正在获取 xml 提要并从文本中创建图像。我想做的是将链接文本着色为与常规文本不同的颜色。我正在遍历文本以查找链接,但无法弄清楚如何为该文本着色。
【问题讨论】:
imagetttftext() 只能绘制单一颜色。您无法更改它或嵌入 html-ish 颜色代码来动态更改文本颜色。您必须将文本分成多个块,每个块都用一种颜色绘制。
这意味着您必须使用imagettfbbox() 计算每个字符串块的开始/停止位置,并相应地调整imagetttftext() 中的坐标。
评论跟进:
好的,单独的标签内容,链接是不同的颜色。第一步是预处理字符串并沿链接边界将其拆分,因此您最终会得到一系列“文本/链接/文本/链接/文本”块。之后,它只是一个循环:
$start_x = 5;
$start_y = 20; // initial x/y coords of text
$fontsize = 14;
$font = 'font.ttf';
$angle = 0;
$black = imagecolorallocate($im, 0, 0, 0);
$linkcolor = imagecolorallocate($im, ?, ? ,?);
foreach ($string_chunks as $chunk) {
// get coordinates of bounding box containing text
$coords = imagegettfbbox($fontsize, $angle, $font, $chunk);
$end_x = $coords[4]; // as per imagetttfbbox() doc page
$end_y = $coords[5]; // x,y coords of top right corner of bounding box
// figure out which color to draw in
$color_to_draw = is_link($chunk) ? $linkcolor : $black;
// draw the text chunk
imagettftext($im, $fontsize, $angle, $start_x, $start_y, $color_to_draw, $font, $chunk);
// adjust starting coordinates to the END of the just-drawn text
$start_x += $end_x;
$start_y += $end_y;
}
如果没有足够的空间,您可能需要随时调整坐标 每个文本块,或者在得到它的边界框之前在字符串中添加一个空格。
【讨论】:
$im 参数(因为它不适用于图像,只是计算一些文本内容)。如果你删除它应该可以工作。
我知道有imagefontwidth() 和imagefontheight() 可以获取字体字符的高度和宽度。但是,这只适用于内置字体或加载了imageloadfont() 的字体,我认为它们不支持 TTF 文件。但是如果你使用它,计算每个块的坐标会相当容易。
例如:
<?php
// Image:
$image = imagecreatetruecolor(200, 200);
// First built-in font:
$font = 1;
// X and Y coordinates of the 5th character in the 7th row:
$x = imagefontwidth($font) * 4;
$y = imagefontheight($font) * 6;
// Put character onto image, with white color:
imagestring($image, $font, $x, $y, 'H', 0xffffff);
?>
(请注意,尽管我在代码中使用了0xffffff 作为颜色,但还是建议尽可能使用imagecolorallocate())
【讨论】: