我将获取一个xml提要,并从文本创建图像。我想做什么,它的颜色链接文本不同于常规文本的颜色。我正在遍历文本以查找链接,但无法弄清楚如何为文本着色。
发布于 2010-08-23 22:53:10
imagetttftext()只能绘制一种颜色。你不能改变它,或者嵌入html-ish颜色代码,来动态改变文本的颜色。你必须将你的文本分成多个块,每个块都用一种颜色绘制。
这意味着您必须使用imagettfbbox()计算每个字符串块的开始/停止位置,并相应地调整您在imagetttftext()中的坐标。
评论后续:
好的,单个标签内容,链接有不同的颜色。第一步是对字符串进行预处理,并沿着链接边界将其拆分,这样您就得到了一系列"text / link / text / link / text“块。在那之后,它只是一个循环:
$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;
}如果每段文本之间没有足够的空间,您可能需要调整坐标,或者在获得其边界框之前在字符串中放入一个空格。
发布于 2010-08-23 23:19:01
我知道有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() )
https://stackoverflow.com/questions/3548580
复制相似问题