php - 如何在 PHP 中使用 Imagick 包装文本,以便将其绘制为多行文本?

标签 php text imagick annotate

PHP 中的 Imagick 库允许您在图像上绘制文本。

我如何告诉 Imagick 基于一些有界文本框来包装文本,以便单词显示为多行文本而不是单行?

最佳答案

用法:

list($lines, $lineHeight) = wordWrapAnnotation($image, $draw, $msg, 140);
for($i = 0; $i < count($lines); $i++)
    $image->annotateImage($draw, $xpos, $ypos + $i*$lineHeight, 0, $lines[$i]);

功能:

/* Implement word wrapping... Ughhh... why is this NOT done for me!!!
    OK... I know the algorithm sucks at efficiency, but it's for short messages, okay?

    Make sure to set the font on the ImagickDraw Object first!
    @param image the Imagick Image Object
    @param draw the ImagickDraw Object
    @param text the text you want to wrap
    @param maxWidth the maximum width in pixels for your wrapped "virtual" text box
    @return an array of lines and line heights
*/
function wordWrapAnnotation(&$image, &$draw, $text, $maxWidth)
{
    $words = explode(" ", $text);
    $lines = array();
    $i = 0;
    $lineHeight = 0;
    while($i < count($words) )
    {
        $currentLine = $words[$i];
        if($i+1 >= count($words))
        {
            $lines[] = $currentLine;
            break;
        }
        //Check to see if we can add another word to this line
        $metrics = $image->queryFontMetrics($draw, $currentLine . ' ' . $words[$i+1]);
        while($metrics['textWidth'] <= $maxWidth)
        {
            //If so, do it and keep doing it!
            $currentLine .= ' ' . $words[++$i];
            if($i+1 >= count($words))
                break;
            $metrics = $image->queryFontMetrics($draw, $currentLine . ' ' . $words[$i+1]);
        }
        //We can't add the next word to this line, so loop to the next line
        $lines[] = $currentLine;
        $i++;
        //Finally, update line height
        if($metrics['textHeight'] > $lineHeight)
            $lineHeight = $metrics['textHeight'];
    }
    return array($lines, $lineHeight);
}

关于php - 如何在 PHP 中使用 Imagick 包装文本,以便将其绘制为多行文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5746537/

相关文章:

php - 从 pgadmin 和 doctrine ORM 调用存储过程时的不同结果

php - 用于在 javascript 中使用和不使用引号拆分单词的 rawurldecode 和 regexp?

python - 需要帮助在同一目录中的文件夹中创建 txt 文件

在 C 中创建按字母顺序排列的 .txt 文件的二进制搜索

macos - Mac 聚光灯 : How does it work so quickly?

php - 使用 PHP 将 PDF 转换为 JPG

php - 通过扩展的 php 生成 4 位 token

php - 如何在一个 SQL 表中创建无限类别子项

php - Imagick 在使用 PHP 将 SVG 转换为 JPG 时不使用自定义字体

php - 如何使用 php 将数据存储在图像中?