【问题标题】:PHP: color hyperlink before create imagePHP:创建图像之前的颜色超链接
【发布时间】:2011-04-02 16:36:06
【问题描述】:

我正在获取 xml 提要并从文本中创建图像。我想做的是将链接文本着色为与常规文本不同的颜色。我正在遍历文本以查找链接,但无法弄清楚如何为该文本着色。

【问题讨论】:

    标签: php text colors hyperlink


    【解决方案1】:

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

    如果没有足够的空间,您可能需要随时调整坐标 每个文本块,或者在得到它的边界框之前在字符串中添加一个空格。

    【讨论】:

    • xml 的内容发生了变化,所以我将如何动态计算位置。或者有比 imagettftext 更好的方法吗?
    • 您是在绘制文字 XML 源代码吗?还是只是一些单独标签的内容?
    • 各个标签的内容。
    • 在 $coords = imagettfbbox($im, $fontsize, $angle, $font, $chunk);行我收到错误“imagettfbbox() 的参数计数错误”
    • 哎呀,该函数不采用$im 参数(因为它不适用于图像,只是计算一些文本内容)。如果你删除它应该可以工作。
    【解决方案2】:

    我知道有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()

    【讨论】:

    • imageloadfont() 的问题是它不支持 ttf 字体,我需要使用 ttf 字体进行品牌推广。
    猜你喜欢
    • 1970-01-01
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 2015-02-28
    • 2016-09-04
    • 1970-01-01
    • 2013-03-07
    相关资源
    最近更新 更多