人民。
我有轻微的问题与图像上的GD2文本。我有一切工作,现在我尝试添加文本的图像,可以在图像中包装。
例如,我有宽度为200px的图像和大块文本。如果你使用imagettftext(),文本会超出图像的边界,实际上只有部分文本是可见的。我尝试过使用Zend的文本换行功能,但它在这里并不总是产生准确的结果(并不是说它不能工作,只是在本例中不能工作)。
是否有一些专用的GD2方法来设置文本应该适合的宽度框,如果它到达框的边界,它应该在新行中继续?
发布于 2012-03-26 18:19:48
不确定这是你想要的,但是,你可以试试这个:
function wrap($fontSize, $fontFace, $string, $width){
$ret = "";
$arr = explode(' ', $string);
foreach ( $arr as $word ){
$teststring = $ret.' '.$word;
$testbox = imagettfbbox($fontSize, 0, $fontFace, $teststring);
if ( $testbox[2] > $width ){
$ret.=($ret==""?"":"\n").$word;
} else {
$ret.=($ret==""?"":' ').$word;
}
}
return $ret;
}发布于 2013-04-22 22:43:36
safarov中的函数包含一个针对我的用例演示的小bug。
veryloooooooooooooongtextblablaOVERFLOWING
this
should
be
one
line我的解决方案是简单地分别检查每个单词的宽度,并选择性地剪切单词,直到它适合$width (或者,如果长度为0,则取消剪切)。然后,我继续进行正常的换行。结果类似于:
veryloooooooooooooongtextblabla
this should be one line下面是修改后的函数:
function wrap($fontSize, $fontFace, $string, $width) {
$ret = "";
$arr = explode(" ", $string);
foreach ( $arr as $word ){
$testboxWord = imagettfbbox($fontSize, 0, $fontFace, $word);
// huge word larger than $width, we need to cut it internally until it fits the width
$len = strlen($word);
while ( $testboxWord[2] > $width && $len > 0) {
$word = substr($word, 0, $len);
$len--;
$testboxWord = imagettfbbox($fontSize, 0, $fontFace, $word);
}
$teststring = $ret.' '.$word;
$testboxString = imagettfbbox($fontSize, 0, $fontFace, $teststring);
if ( $testboxString[2] > $width ){
$ret.=($ret==""?"":"\n").$word;
} else {
$ret.=($ret==""?"":' ').$word;
}
}
return $ret;
}发布于 2012-03-26 18:16:29
不幸的是,我不认为有一种简单的方法可以做到这一点。您所能做的最好的就是近似计算图像宽度,以及当前字体中的文本可以在第n个字符上手动容纳和断开的字符数。
如果你使用等宽字体(我知道不太可能),你可以得到一个准确的结果,因为它们是均匀分布的。
https://stackoverflow.com/questions/9870287
复制相似问题