php imagettftext 生成文字实现自动换行并设置行高
作者:xlnxin发布时间:2023-12-03分类:其他教程浏览:1563
导读:/** * 处理规定宽度内自动换行(imagettftext) &nb...
/**
* 处理规定宽度内自动换行(imagettftext)
* @param $card 画板
* @param $str string 字符串
* @param $width int 规定宽度
* @param $x int 文字生成的x位置
* @param $y int 文字生成的y位置
* @param $fontSize int 字体大小
* @param $font string 字体
* @param $color 字体颜色
* @param $rowHeight 行高
* @return bool
*/
function handleTextAlign($card, $str, $width, $x, $y, $fontSize, $font, $color, $rowHeight)
{
$content = "";
$row = 0;
$boxText = [];
for ($i = 0; $i < mb_strlen($str, 'utf8'); $i++) {
$letter = mb_substr($str, $i, 1, 'utf-8');//当前的字
$nextLetter = mb_substr($str, $i + 1, 1, 'utf-8');//当前的字
//第一 获取下一个拼接好的宽度 如果下一个拼接好的已经大于width了,就在当前的换行 如果不大于width 就继续拼接
$content .= $letter;
$nextStr = $content . $nextLetter;
$fontBox = imagettfbbox($fontSize, 0, $font, $nextStr);
if (($fontBox[2] > $width) && ($content !== "")) { //大于限制宽度 直接换行 这一行写入画布
$row = $row + 1;
$boxText[] = $content;
$content = "";
} else if ($i + 1 == mb_strlen($str, 'utf8')) {
$boxText[] = $content;
}
}
//多行减小字体大小
$fontSize = $fontSize - ($row * 2);
if ($row > 0){
//y方向的起始位置
$y = $y - ($row + 1) * $rowHeight;
}
foreach ($boxText as $item){
imagettftext($card, $fontSize, 0, $x, $y, $color, $font, $item);
$y += $fontSize + $rowHeight;
}
return true;
}标签:php
- 其他教程排行
- 最近发表
