How can I wrap text using Imagick in PHP so that it is drawn as multiline text?

前端 未结 5 1475
悲哀的现实
悲哀的现实 2020-12-05 16:54

The Imagick library in PHP allows you to draw text on top of an image.

How can I tell Imagick to wrap the text based upon some bounded text box, so that the words ap

5条回答
  •  眼角桃花
    2020-12-05 17:30

    I found a bug with @BMiner's function where it returns a lineheight of 0 when there is only one word.

    I ended up re-writing it in one loop using array functions. I kept the parameters the same so it works with current implementations.

    I used preg_split instead so it works well with extra or double spaces, tabs, and line-breaks.

    function wordWrapAnnotation($image, $draw, $text, $maxWidth)
    {
        $words = preg_split('%\s%', $text, -1, PREG_SPLIT_NO_EMPTY);
        $lines = array();
        $i = 0;
        $lineHeight = 0;
    
        while (count($words) > 0)
        {
            $metrics = $image->queryFontMetrics($draw, implode(' ', array_slice($words, 0, ++$i)));
            $lineHeight = max($metrics['textHeight'], $lineHeight);
    
            if ($metrics['textWidth'] > $maxWidth or count($words) < $i)
            {
                $lines[] = implode(' ', array_slice($words, 0, --$i));
                $words = array_slice($words, $i);
                $i = 0;
            }
        }
    
        return array($lines, $lineHeight);
    }
    

提交回复
热议问题