Wrap and center text in gd and php

I have a line of text that I need to wrap and center in a GD image. I also use the ttf font. Can anything help me?

I managed to get some text to do the following, but now I need to center it:

function wrap($fontSize, $angle, $fontFace, $string, $width){

    $ret = "";

    $arr = explode(' ', $string);

    foreach ( $arr as $word ){

        $teststring = $ret.' '.$word;
        $testbox = imagettfbbox($fontSize, $angle, $fontFace, $teststring);
        if ( $testbox[2] > $width ){
            $ret.=($ret==""?"":"\n").$word;
        } else {
            $ret.=($ret==""?"":' ').$word;
        }
    }

    return $ret;
}
+3
source share
3 answers

Center both horizontally and vertically: get half the height from imagettfbbox of the whole text (with new lines) and align it with half the height of your image ( $start_x).

, ttfbox ($h) ($w). , + $w $start_x, $h $start_x, , .

+1

valentijn de Pagter php net ( , imagettfbbox(), ), , . :

imagettfbbox

+2

, . imagettftext, . \n . , .

            $description=$property['description'];
            $len=strlen($description);
            $str="";
            $c=0;
            for($i=0;$i<$len;$i++){
                $chr=substr($description,$i,1);
                $str.=$chr;
                if($c>40 && $chr==" ") {
                    $str.="\n";
                    $c=0;   
                }
                $c++;
                }
            $result=$str;
            imagettftext($img, 15, 0, $x - 60, $descmgn, $textcolor, $font, $result);
0

Source: https://habr.com/ru/post/1792915/


All Articles