note 51563 deleted from function.imagettfbbox by cmb
| From: | cmb@php.net | Date: | Sun, 04 Dec 2016 11:58:23 +0000 |
| Subject: | note 51563 deleted from function.imagettfbbox by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-208167@lists.php.net to get a copy of this message | ||
Note Submitter: vegard at I dot DONT dot WANT dot SPAM dot programmer dot no
----
Here is a function that wordwraps text you want to print, allows to specify where the text should be
printed, what the maximum width should be, and returns the height used.
<?php
function printWordWrapped(&$image, $top, $left, $maxWidth, $font, $color, $text,
$textSize) {
$words = explode(' ', strip_tags($text)); // split the text into an array
of single words
$line = '';
while (count($words) > 0) {
$dimensions = imagettfbbox($textSize, 0, $font, $line.'
'.$words[0]);
$lineWidth = $dimensions[2] - $dimensions[0]; // get the length of this
line, if the word is to be included
if ($lineWidth > $maxWidth) { // if this makes the text wider that
anticipated
$lines[] = $line; // add the line to the others
$line = ''; // empty it (the word will be added outside
the loop)
}
$line .= ' '.$words[0]; // add the word to the current sentence
$words = array_slice($words, 1); // remove the word from the array
}
if ($line != '') { $lines[] = $line; } // add the last line to the others,
if it isn't empty
$lineHeight = $dimensions[1] - $dimensions[7]; // the height of a single line
$height = count($lines) * $lineHeight; // the height of all the lines total
// do the actual printing
$i = 0;
foreach ($lines as $line) {
imagettftext($image, $textSize, 0, $left, $top + $lineHeight * $i, $color,
$font, $line);
$i++;
}
return $height;
}
?>