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