/* 文字自動換行
* @param $card 畫板
* @param $pos 數組,top距離畫板頂端的距離,fontsize文字的大小,width寬度,left距離左邊的距離,hang_size行高
* @param $str 要寫的字符串
* @param $iswrite 是否輸出,ture, 花出文字,false只計算佔用的高度
* @param $nowHeight 已寫入行數;
* @param $second 數組 left 記錄換行後據x座標 ,width 記錄換行後最大寬; , maxline 記錄最大容許最大行數
* @return 數組 tp:本次寫入行數 nowHeight:一共寫入行數 residueStr:截取未寫完的字符串 height:最後一行據頂部的高度
*/
function textalign($card, $pos, $str, $iswrite,$fontpath,$nowHeight,$second){
$_str_h = $pos["top"];//文字在整個圖片距離頂端的位置,也就是y軸的像素距離
$fontsize = $pos["fontsize"];//文字的大小
$width = $pos["width"];//設置文字換行的寬帶,也就是多寬的距離,自動換行
$margin_lift = $pos["left"];//文字在整個圖片距離左邊的位置,也就是X軸的像素距離
$hang_size = $pos["hang_size"];// 這個是行高
$temp_string = "";
$secondCk = ""; //換號的標示,已換行true ,未換行false;
$font_file =$fontpath;//字體文件,在個人同級目錄的Fonts文件夾下面
$tp = 0;
$font_color = imagecolorallocate($card, $pos["color"][0], $pos["color"][1], $pos["color"][2]);
for ($i = 0; $i < mb_strlen($str,'utf8'); $i++) {
$box = imagettfbbox($fontsize, 0, $font_file, $temp_string);
$_string_length = $box[2] - $box[0];
$temptext = mb_substr($str, $i, 1,'utf-8');//拆分字符串
$temp = imagettfbbox($fontsize, 0, $font_file, $temptext);//用來測量每一個字的大小
if($secondCk){//若是換行,進入判斷賦值
if(is_array($second)){//若是傳入換行後參數,則使用.
$width = $second['width'];
$margin_lift = $second['left'];
}
}
if($second['maxline']){
//若是已經寫入最大行數
if($nowHeight == $second['maxline']){
//獲取原字符串長度
$strlong = mb_strlen($str,'utf8');
//抓取剩餘字符串
$residueStr ='';
$residueStr .= mb_substr($str, $i, $strlong - $i,'utf-8');
$cc = $strlong - $i;
break;
}
}
if ($_string_length + $temp[2] - $temp[0] < $width) {
$temp_string .= mb_substr($str, $i, 1,'utf-8');
if ($i == mb_strlen($str,'utf8') - 1) {
$_str_h += $hang_size;
$tp++;//用來記錄有多少行
$nowHeight++;//記錄一共寫入多少行
if ($iswrite) {//若是傳入的參數是false,只作測量,不進行繪製輸出
imagettftext($card, $fontsize, 0, $margin_lift, $_str_h, $font_color, $font_file, $temp_string);
}
}
} else {
$texts = mb_substr($str, $i, 1,'utf-8');
$isfuhao = preg_match("/[\\pP]/u", $texts) ? true : false;//用來判斷最後一個字是否是符合,
if ($isfuhao) {//若是是符號,咱們就不換行,把符合添加到最後一個位置去
$temp_string .= $texts;
} else {
$i--;
}
$_str_h += $hang_size;
$tp++;
$nowHeight++;//記錄一共寫入多少行
if($iswrite){
imagettftext($card, $fontsize, 0, $margin_lift, $_str_h, $font_color, $font_file, $temp_string);
}
$temp_string = "";
$secondCk = true;//做爲是否已換行的標誌
}
}
$strdata['tp'] = $tp ;
$strdata['residueStr'] = $residueStr ;
$strdata['nowHeight'] = $nowHeight ;
$strdata['height'] = $_str_h;
return $strdata;
}數組
作一個心中有料的人.<shiyan_stz@163.com>字體