简体   繁体   中英

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 am using a ttf font as well. Can anything give me some assistance please?

I have managed to get some text to wrap doing the following, but now i need to get it to center:

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

User valentijn de Pagter provides, on php net manual, a nice function to calculate the box (I see you're using imagettfbbox(), indeed) and from the array it returns calculate how to center text. You can find it here:

center text with imagettfbbox

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

Now split text by new lines, create ttfbox for every line and get it's height ( $h ) and half width ( $w ). Draw line starting from half image width + $w and $start_x , add $h to $start_x , repat until all lines are written.

This is what I did. using the imagettftext function, you can add new line marks and continue on to the next line. You can add \\n to the string after a certain amount of characters. This example will only break on spaces, so words won't get cut off.

            $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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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