2011-05-29 111 views
3

我創建透明文本 - >與PHP的圖像,並迄今如此好。唯一的問題是,我希望能夠由於固定寬度而具有文字自動換行功能。或者,也可以在文本中插入分隔符。有沒有人有過這樣的經驗?這裏是我的代碼...在多行中使用imagettftext函數?任何人之前做過?

<?php 

$font = 'arial.ttf'; 
$text = 'Cool Stuff! this is nice LALALALALA LALA HEEH EHEHE'; 
$fontSize = 20; 

$bounds = imagettfbbox($fontSize, 0, $font, $text); 

$width = abs($bounds[4]-$bounds[6]); 
$height = abs($bounds[7]-$bounds[1]); 



$im = imagecreatetruecolor($width, $height); 
imagealphablending($im, false); 
imagesavealpha($im, true); 


$trans = imagecolorallocatealpha($im, 255, 255, 255, 127); 

// Create some colors 
$white = imagecolorallocate($im, 255, 255, 255); 
$grey = imagecolorallocate($im, 128, 128, 128); 
$black = imagecolorallocate($im, 0, 0, 0); 


imagecolortransparent($im, $black); 
imagefilledrectangle($im, 0, 0, $width, $height, $trans); 


// Add the text 
imagettftext($im, $fontSize, 0, 0, $fontSize-1, $grey, $font, $text); 


imagepng($im, "image.png"); 
imagedestroy($im); 


?> 

回答

5

只要發生爆炸空間的文字將文字數組,然後開始通過的話陣列循環,通過imagettfbbox,看看測試每增加一個新字線建設它會創建一個超出您設置的最大寬度的寬度。如果是這樣,請在新的一行上開始下一個單詞。我發現簡單地創建一個添加了特殊換行符的新字符串更容易,然後再次分解該字符串以創建一個行數組,每個行將分別寫入最終圖像。

事情是這樣的:

$words = explode(" ",$text); 
$wnum = count($words); 
$line = ''; 
$text=''; 
for($i=0; $i<$wnum; $i++){ 
    $line .= $words[$i]; 
    $dimensions = imagettfbbox($font_size, 0, $font_file, $line); 
    $lineWidth = $dimensions[2] - $dimensions[0]; 
    if ($lineWidth > $maxwidth) { 
    $text.=($text != '' ? '|'.$words[$i].' ' : $words[$i].' '); 
    $line = $words[$i].' '; 
    } 
    else { 
    $text.=$words[$i].' '; 
    $line.=' '; 
    } 
} 

凡豎線是換行符。

+0

此代碼的工作赫然,但我只是有一個問題......你怎麼又把每條線分開? – 2012-04-13 00:43:46

+2

代替迭代線簡單地添加PHP_EOL當線變得太長,如下所示:如果'($的lineWidth <$ maxLineWidth){ \t \t \t \t \t \t \t $ newText = $值。 ''; \t \t \t \t \t \t}其他{ \t \t \t \t \t \t \t $ newText = PHP_EOL。 $值; \t \t \t \t \t \t}' – Yevgeniy 2012-05-15 03:37:53

9

試試這個

$text = 'Cool Stuff! this is nice LALALALALA LALA HEEH EHEHE'; 
$text = wordwrap($_POST['title'], 15, "\n"); 

我希望它可以幫助別人,因爲我認爲它toooooo遲到了你......

+2

今天幫助了我。 2年後... :-) – Preben 2016-05-21 12:45:54

+2

今天幫了我,謝謝! – 2016-06-03 11:04:15

相關問題