1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?php header ("Content-type: image/png"); // header('Content-Type: text/html; charset=utf-8'); mb_internal_encoding("UTF-8"); // 设置编码 function autowrap($fontsize, $angle, $fontface, $string, $width,&$line) { // 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度 $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); // var_dump($teststr); // var_dump($testbox); // 判断拼接后的字符串是否超过预设的宽度 if (($testbox[2] > $width) && ($content !== "")) { $content .= "\n"; $line ++; } $content .= $l; } return $content; } // echo '<pre>'; $text = "前段时间用 PH时,为了G很久前段时间练习使 GD 库时,为了本的自动换行纠结了很久前段时间练习使用 PH用 PHP 的 GD 库时,为了文本的自动换行纠结了为了文本的自动换行纠结了很久前段时间练习使用 PHP 的 GD 库时,为了文本的自动换行纠结了很久虽然可以通过插入 \n 实现换行,但考虑到文本中既有中文又有英文,强制限定每多少个文字就换行的效果很差。后来终于找到了一个英文下的自动换行的方法,其大概原理是将空格作为分隔符,将字符串分割为一个个单词,然后再一个接一个地拼接在一起,判断其长度是否超过画布,若超过则换行再拼接,否则继续拼接。考虑到中文需要将每个文字都拆开,所以我进行了一点修改,完整代码如下。"; $line = 1; $fone_size = 8; $text = autowrap($fone_size, 0, "simsun.ttc", $text, 280,$line); // 自动换行处理 // print('line:'.$line); // die('test'); $bg = imagecreatetruecolor(300, $fone_size*1.75*$line); // 创建画布 $white = imagecolorallocate($bg, 255, 255, 255); // 创建白色 // 若文件编码为 GB2312 请将下行的注释去掉 // $text = iconv("GB2312", "UTF-8", $text); imagettftext($bg, $fone_size, 0, 10, 30, $white, "simsun.ttc", $text); imagepng($bg); imagedestroy($bg); ?> |