Is there a word wrap function for GD2 in php?

陌路散爱 提交于 2019-12-04 17:41:39

Not sure its what you looking for but, you can try this:

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

The function from safarov contains a small bug which demonstrated for my user case. If I sent a word larger than $width, it would newline every word afterwards, so for example:

veryloooooooooooooongtextblablaOVERFLOWING
this 
should 
be 
one 
line

The reason is, imagettfbox will always be > $width with that "malicious" word inside text. My solution was to simply check each word width separately and optionally cut the word until it fits $width (or cancel the cutting if we get to length 0). Then I proceed with normal wordwrapping. The result is something like:

veryloooooooooooooongtextblabla
this should be one line

Here's the modified function:

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

Unfortunately I don't think there's an easy way of doing this. The best you can do is to approximately calculate your image width and how many characters your text in its current font can fit and break it manually on that n'th character.

If you are using a monospace fonts (unlikely, I know), you can get an accurate result as they are evenly spaced.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!