php GD imagettftext生成文字 自動換行 設定行高
阿新 • • 發佈:2021-02-04
技術標籤:phpGDimagettftextphp
/* 文字自動換行 * @param $card 畫板 * @param $str 要換行的文字 * @param $width 文字顯示的寬度,到達這個寬度自動換行 * @param $x 基礎 x座標 * @param $y 基礎Y座標 * @param $fontsize 文字大小 * @param $fontfile 字型 * @param $color array 字型顏色 * @param $rowheight 行間距 * @param $maxrow 最多多少行 */ function textalign($card, $str, $width, $x,$y,$fontsize,$fontfile,$color,$rowheight,$maxrow) { $tempstr = ""; $row = 0; for ($i = 0; $i < mb_strlen($str, 'utf8'); $i++) { if($row >= $maxrow) { break; } //第一 獲取下一個拼接好的寬度 如果下一個拼接好的已經大於width了,就在當前的換行 如果不大於width 就繼續拼接 $tempstr = $tempstr.mb_substr($str, $i, 1, 'utf-8');//當前的文字 $nextstr = $tempstr.mb_substr($str, $i+1, 1, 'utf-8');//下一個字串 $nexttemp = imagettfbbox($fontsize, 0, $fontfile, $nextstr);//用來測量每個字的大小 $nextsize = ($nexttemp[2]-$nexttemp[0]); if($nextsize > $width-10) {//大於整體寬度限制 直接換行 這一行寫入畫布 $row = $row+1; // $card->imageText($tempstr,$fontsize,$color,$x,$y,$width,1); imagettftext($card, $fontsize, 0, $x, $y, $color, $fontfile, $tempstr); $y = $y+$fontsize+$rowheight; $tempstr = ""; } else if($i+1 == mb_strlen($str, 'utf8') && $nextsize<$width-10){ // $card->imageText($nextstr,$fontsize,$color,$x,$y,$width,1); imagettftext($card, $fontsize, 0, $x, $y, $color, $fontfile, $tempstr); } } return true; }