Vienoje eilutėje tekstas ne visada telpa į tam tikrą paveikslėlio plotį, tada reikia perkelti tekstą į naują eilutę, priklausomai nuo pločio. Bet jei plotis mažiau nei vienas žodis, tada reikės šamano būgno ir burti toliau. PHP kodo pavyzdys sukuria nurodyto pločio teksto paveiksliuką:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | <?php //turinio tipas header( 'Content-Type: image/png' ); //šriftas $font = 'arial.ttf' ; //šrifto dydis $font_size = 10; //paveikslėlio plotis $width = 100; //atstumas nuo teksto kraštų $margin = 5; //tekstas $text = "Kur kada kodėl ir kaip, o dabar kur kada kodėl ir kaip?" ; //padaliname tekstą į žodžių $text_a = explode ( ' ' , $text ); $text_new = '' ; foreach ( $text_a as $word ){ //sukuriame naują tekstą, pridedame žodį, ir apskaičiuoti teksto parametrus $box = imagettfbbox( $font_size , 0, $font , $text_new . ' ' . $word ); //jei eilutė telpa į nurodytą plotį, tai pridedame žodį su tarpu, jei netelpa, tai pridedame žodį kitoje eilutėje if ( $box [2] > $width - $margin *2){ $text_new .= "\n" . $word ; } else { $text_new .= " " . $word ; } } //triname pirmą tarpą $text_new = trim( $text_new ); //naujo teksto parametrai $box = imagettfbbox( $font_size , 0, $font , $text_new ); //naujo teksto aukštis $height = $box [1] + $font_size + $margin * 2; //sukuriame paveiksliuką $im = imagecreatetruecolor( $width , $height ); //sukuriame spalvą $white = imagecolorallocate( $im , 255, 255, 255); $black = imagecolorallocate( $im , 0, 0, 0); //nudažome paveiksliuką spalva imagefilledrectangle( $im , 0, 0, $width , $height , $white ); //įdedame tekstą į paveiksliuką imagettftext( $im , $font_size , 0, $margin , $font_size + $margin , $black , $font , $text_new ); //grąžiname paveiksliuką imagepng( $im ); //ištriname paveiksliuką iš atminties imagedestroy( $im ); |