回覆:Sohel Taslim (03-Aug-2007 06:19)
感謝您的函式,我稍微修改了一下。在新版本中,行之間有相同的間距(您範例中的 g 會在行之間產生較大的間距)- 由參數 '$Leading' 設定。
我使用了 for 迴圈來獲得更好的效能,並稍微精簡了其餘部分 :)
/**
* @name : makeImageF
*
* 使用選定的字型從文字建立影像的函式。對齊影像中的文字 (0-左對齊, 1-右對齊, 2-置中)。
*
* @param String $text : 要轉換為影像的字串。
* @param String $font : 文字的字型名稱。將字型檔案放在同一個資料夾中。
* @param int $Justify : 對齊影像中的文字 (0-左對齊, 1-右對齊, 2-置中)。
* @param int $Leading : 行之間的間距。
* @param int $W : 影像的寬度。
* @param int $H : 影像的高度。
* @param int $X : 文字在影像中的 x 座標。
* @param int $Y : 文字在影像中的 y 座標。
* @param int $fsize : 文字的字型大小。
* @param array $color : 文字顏色的 RGB 顏色陣列。
* @param array $bgcolor : 背景的 RGB 顏色陣列。
*
*/
function imagettfJustifytext($text, $font="CENTURY.TTF", $Justify=2, $Leading=0, $W=0, $H=0, $X=0, $Y=0, $fsize=12, $color=array(0x0,0x0,0x0), $bgcolor=array(0xFF,0xFF,0xFF)){
$angle = 0;
$_bx = imageTTFBbox($fsize,0,$font,$text);
$s = split("[\n]+", $text); // 行的陣列
$nL = count($s); // 行數
$W = ($W==0)?abs($_bx[2]-$_bx[0]):$W; // 如果寬度未由程式設計師初始化,則會偵測並指派完美的寬度。
$H = ($H==0)?abs($_bx[5]-$_bx[3])+($nL>1?($nL*$Leading):0):$H; // 如果高度未由程式設計師初始化,則會偵測並指派完美的高度。
$im = @imagecreate($W, $H)
or die("無法初始化新的 GD 影像串流");
$background_color = imagecolorallocate($im, $bgcolor[0], $bgcolor[1], $bgcolor[2]); // RGB 背景顏色。
$text_color = imagecolorallocate($im, $color[0], $color[1], $color[2]); // RGB 文字顏色。
if ($Justify == 0){ //左對齊
imagettftext($im, $fsize, $angle, $X, $fsize, $text_color, $font, $text);
} else {
// 建立包含所有國際字元的字母數字字串 - 包括大小寫
$alpha = range("a", "z");
$alpha = $alpha.strtoupper($alpha).range(0, 9);
// 使用字串來判斷行的高度
$_b = imageTTFBbox($fsize,0,$font,$alpha);
$_H = abs($_b[5]-$_b[3]);
$__H=0;
for ($i=0; $i<$nL; $i++) {
$_b = imageTTFBbox($fsize,0,$font,$s[$i]);
$_W = abs($_b[2]-$_b[0]);
//定義 X 座標。
if ($Justify == 1) $_X = $W-$_W; // 右對齊
else $_X = abs($W/2)-abs($_W/2); // 置中對齊
// 定義 Y 座標。
$__H += $_H;
imagettftext($im, $fsize, $angle, $_X, $__H, $text_color, $font, $s[$i]);
$__H += $Leading;
}
}
return $im;
}