21,886
社区成员
发帖
与我相关
我的任务
分享
$font = 'c:/windows/fonts/simsun.ttf';
$text = iconv('gbk', 'utf-8', '图片上给定一个方框(知道4点坐标),需要把一串文本分成N行输出到图片上,每行文字不能超过方框的宽度,N行总高度也不能超过方框。如果总高度会超过方框高度,则缩小字体,直至文字能全部显示在方框中。');
$im = imagecreate(200, 200);
$bg = imagecolorallocate($im, 255, 255, 255);
$pen = imagecolorallocate($im, 0, 0, 0);
$style = array( $pen, $pen, $bg, $bg, $pen );
imagesetstyle($im, $style);
iconv_set_encoding("internal_encoding", "UTF-8"); //我偏好 iconv,用 mb 也是一样的
$sx = 20;
$sy = 20;
$ex = 180;
$ey = 180;
$h = 30; //行高
$loop = true;
while($loop) {
$size = $h / 3 * 2; //字体大小
$s = '';
$r = 1;
imagefilledrectangle($im, $sx, $sy, $ex, $ey, $bg);
imagerectangle($im, $sx, $sy, $ex, $ey, IMG_COLOR_STYLED);
for($i=0; $i<iconv_strlen($text); $i++) {
$c = iconv_substr($text, $i, 1);
$box = ImageTTFBBox($size, 0, $font, $s.$c);
if($box[2] - $box[0] < $ex - $sx) $s .= $c;
else {
if($h*$r > $ey - $sy) break;
imagettftext($im, $size, 0, $box[0]+$sx, $sy+$h*$r, $pen, $font, $s);
$s = '';
$r++;
$i--;
}
}
if($s) {
if($h*$r > $ey - $sy) {
$h--;
continue;
}
$loop = false;
imagettftext($im, $size, 0, $box[0]+$sx, $sy+$h*$r, $pen, $font, $s);
}
}
imagettftext($im, $size, 0, $sx, $ey+$h, $pen, $font, "size:$size");
imagegif($im);