Issue
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 appear as multiline text rather than a single line?
Solution
I have been using @Sarke's version successfully for a while, but I noticed there is an infinite loop if a word is longer than the $maxWidth. Here is a version that fixes the infinite loop:
function wordWrapAnnotation($image, $draw, $text, $maxWidth)
{
$text = trim($text);
$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);
// check if we have found the word that exceeds the line width
if ($metrics['textWidth'] > $maxWidth or count($words) < $i)
{
// handle case where a single word is longer than the allowed line width (just add this as a word on its own line?)
if ($i == 1)
$i++;
$lines[] = implode(' ', array_slice($words, 0, --$i));
$words = array_slice($words, $i);
$i = 0;
}
}
return array($lines, $lineHeight);
}
Answered By - John Langford Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.