繁体   English   中英

在php中有GD2的自动换行功能吗?

[英]Is there a word wrap function for GD2 in php?

人。

我对图像上的GD2文字有轻微问题。 我有一切工作,现在我尝试在图像上添加可以包装在图像中的文本。

例如,我有宽度为200px的图像和大块文本。 如果使用imagettftext()文本超出图像边界,实际上只有部分文本可见。 我曾尝试使用Zend的文本换行功能,但它并不总是在这里产生准确的结果(不是说它不起作用,只是在这种情况下不起作用)。

是否有一些专用的GD2方法来设置文本应该适合的宽度框,如果它碰到那个框的边框,它应该继续在新的行?

不确定它是你在找什么,但你可以试试这个:

 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;
}

来自safarov的函数包含一个针对我的用户案例演示的小错误。 如果我发送了一个大于$ width的单词,那么之后会对每个单词进行换行,例如:

veryloooooooooooooongtextblablaOVERFLOWING
this 
should 
be 
one 
line

原因是,imagettfbox将始终> $ width与文本中的“恶意”单词。 我的解决方案是单独检查每个单词宽度,并可选择剪切单词,直到它适合$ 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;
}

不幸的是,我认为没有一种简单的方法可以做到这一点。 您可以做的最好的方法是近似计算图像宽度以及当前字体中文本可以容纳的字符数,并在第n个字符上手动分解。

如果你使用的是等宽字体(不太可能,我知道),你可以获得准确的结果,因为它们是均匀间隔的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM