note 60673 deleted from function.imagettfbbox by cmb

From: Date: Sun, 04 Dec 2016 11:57:49 +0000
Subject: note 60673 deleted from function.imagettfbbox by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-208162@lists.php.net to get a copy of this message
Note Submitter: Nimja ---- This is a completely rewritten function of "printWordWrapped" because it lacked a few important features. First of all, it started too high with it's text, which was easily fixed. And it has the annoying 'feature' of adding a space in front of every line. Not ideal. But secondly, and more importantly, it didn't support long words or linebreaks. This is all fixed. And I rewrote it for cleaner code. Please note that with the current code you could easily make a vertical align as well if you wanted to. I have not done this myself since it did not fit my own needs (and I'm slightly lazy) Enjoy: <?php function imageTextWrapped(&$img, $x, $y, $width, $font, $color, $text, $textSize, $align="l") { $y += $fontSize; //Correct place for the fonts. $text = str_replace ("\\r", '', $text); //Remove windows line-breaks $srcLines = split ("\\n", $text); //Split text into "lines" $dstLines = Array(); // The destination lines array. foreach ($srcLines as $currentL) { $line = ''; $words = split (" ", $currentL); //Split line into words. foreach ($words as $word) { $dimensions = imagettfbbox($textSize, 0, $font, $line.' '.$word); $lineWidth = $dimensions[4] - $dimensions[0]; // get the length of this line, if the word is to be included if ($lineWidth > $width && !empty($line) ) { // check if it is too big if the word was added, if so, then move on. $dstLines[] = trim($line); //Add the line like it was without spaces. $line = ''; } $line .= $word.' '; } $dstLines[] = trim($line); //Add the line when the line ends. } //Calculate lineheight by common characters. $dimensions = imagettfbbox($textSize, 0, $font, "MXQJPmxqjp123"); //use a custom string to get a fixed height. $lineHeight = $dimensions[1] - $dimensions[5]; // get the heightof this line $align = strtolower(substr($align,0,1)); //Takes the first letter and converts to lower string. Support for Left, left and l etc. foreach ($dstLines as $nr => $line) { if ($align != "l") { $dimensions = imagettfbbox($textSize, 0, $font, $line); $lineWidth = $dimensions[4] - $dimensions[0]; // get the length of this line if ($align == "r") { //If the align is Right $locX = $x + $width - $lineWidth; } else { //If the align is Center $locX = $x + ($width/2) - ($lineWidth/2); } } else { //if the align is Left $locX = $x; } $locY = $y + ($nr * $lineHeight); //Print the line. imagettftext($img, $textSize, 0, $locX, $locY, $color, $font, $line); } } ?>

« previous php.notes (#208162) next »