其他教程

其他教程

Products

当前位置:首页 > 其他教程 >

PHP GD文字水平居中的方法以及换行的用法

GG网络技术分享 2025-03-18 16:17 7


/* 文字自动换行

* @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=12,$maxrow=2)

{

$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;

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){

imagettftext($card, $fontsize, 0, $x, $y, $color, $fontfile, $tempstr);

}

}

return true;

}

PHP GD文字水平居中的方法

$fontSize = 46; //18号字体

$fontWidth = imagefontwidth($fontSize);//获取文字宽度

$textWidth = $fontWidth * mb_strlen($text1);

$x = ceil(($width - $textWidth) / 2); //计算文字的水平位置

imagettftext($image, $fontSize, $x, 282, 222, $white, $zitipath, $name);

标签: 换行 文字

提交需求或反馈

Demand feedback