php画图或者作图时的文字换行

先附上一自定义函数代码

function autowrap($fontsize, $angle, $fontface, $string, $width) {
// 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
$content = "";

// 将字符串拆分成一个个单字 保存到数组 letter 中
for ($i=0;$i < mb_strlen($string);$i++) {
$letter[] = mb_substr($string, $i, 1);
}

foreach ($letter as $l) {
$teststr = $content." ".$l;
$testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
// 判断拼接后的字符串是否超过预设的宽度
if (($testbox[2] > $width) && ($content !== "")) {
$content .= "\n";
}
$content .= $l;
}
$content = mb_convert_encoding($content, "UTF-8", "GB2312");
return $content;
}

能根据给的参数条件自动换行。。。
但是换行之后可能会出现乱码。

优化后的示例
<?php
header("Content-type:text/html;charset=UTF-8");

$string = '曾任设法435发的防撒旦发射大法师发送';//必须为GBK
echo autowrap(12,0,'simhei.ttf',$string,200);

function autowrap($fontsize, $angle, $fontface, $string, $width) {
// 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
$content = "";

$letter = singleWordToArray($string);
foreach ($letter as $l) {
$teststr = $content." ".$l;
$testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
// 判断拼接后的字符串是否超过预设的宽度
if (($testbox[2] > $width) && ($content !== "")) {
$content .= "\n";
}
$content .= $l;
}
$content = mb_convert_encoding($content, "UTF-8", "GB2312");
return $content;
}

function singleWordToArray($str,$spaces=true){
$n = 0;
$len = strlen($str);
$tmp = array();
while ($n<$len){
if(ord(substr($str,$n,1))>0xa0){
$tmp[] = substr($str,$n,2);
$n++;
}else{
$char = trim(substr($str,$n,1));
if($spaces)
{
$tmp[] = $char;
}else{
if ($char!='') $tmp[] = $char;
}
}
$n++;
}//end while
return $tmp;
}
300*300
 文章首页关于迷茫时代关于我写意人生
版权所有:迷茫时代 All rights reserved   
执行时间:0.00456 秒