Search code examples
phptextfontstruetype

php how to fit a text into a box


I have the bounds of a rectangular box. Is it possible to fit a text (with custom font) into the box while not knowing the text size. I mean, is there a php function which sets the proper text size so that the text is fitted into the user-defined box? I do not need text wrapping.

The only functions I found are imagettfbbox and imagettftext.

imagettfbbox does exactly the opposite(gives the bounds, provided a font size) while imagettftext is used to write text on an image, only if fontSize is known.


Solution

  • Are you using php gd? If so, then I would use imagettfbbox. Just define all the parameters except size. Then outside of that loop on size until it is small enough to fit in your defined space. I've done this before. It doesn't do any actual image creative in memory, so it's very fast (much faster than actually creating the image).

    for($size=40;$size>5;$size--){
      $sizearray=imagettfbbox ( $size , 0- , 'font.ttf' , $message );
        $width=$sizearray[0] + $sizearray[4];
        if($width<$threshold/*you define*/){
          //you've got your $size
          break;
        }
    }