webForumDet fria alternativet

GD Library - Skriva text

PHP

1 svar · 343 visningar · startad av Troxy

Medlem sedan mars 20041 505 inlägg
Frågan#1

Hej,

Jag hämtar text från en databas som ska skrivas ut på en bild med hjälp av GD Library. Nu undrar jag om det på något sätt går att begränsa text till en yta. Ex. jag vill att texten ska löpa 200 px, sedan radbrytning. Jag lyckas bara skriva ut allt som en enda lång rad.

Mvh Emil

Medlem sedan juni 20006 031 inlägg
#2

Detta är inget jag har testat nån gång men efter att ha letat lite i manualen så hittade jag detta exempel:

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

?>
253 ms totalt · 4 externa anrop · v20260731065814-full.86ec41c2
124 ms — deklarationer (db)
0 ms — hämta statistik (cache)
126 ms — hämta tråd, inlägg och bilagor (db)
121 ms — ändringar (db)