Main >> Web Development

Text on an arc with PHP & GD

This is a simple function that calculates the position of each letter and prints the text letter by letter onto the given image using the imagettftext function.

 

function imagettftextarc($image, $size, $angle, $x, $y, $r, $color, $fontfile, $text, $dir=false){
    $sbox=imagettfbbox($size, 0, $fontfile, ' ');
    $sbox=($sbox[2]-$sbox[0])*0.1;
    $angle=$angle*M_PI/180;
    foreach(preg_split('//u', $text) AS $t){
        $px=$x+$r*cos($angle);
        $py=$y+$r*sin($angle);
        $dirangle=(360-(M_PI/2+$angle)*180/M_PI+($dir?180:0))%360;
        imagettftext($image, $size, $dirangle, $px, $py, $color, $fontfile, $t);
        $box=imagettfbbox($size, 0, $fontfile, $t);
        $dx=$box[2]-$box[0];
        $da=abs(asin(($dx+$sbox)/$r));
        if($dir){
            $angle-=$da;
        }else{
            $angle+=$da;
        }
    }
}


The paramaters are as follows:

$image: The image to be printed on
$size: Font size
$angle: Starting angle in degrees. 0 points to 3 o'clock
$x, $y: The center of the circle
$r: Radius of the circle
$color: Text color
$fontfile: Font file
$text: The text to be printed on
$dir: Direction of the text (clockwise/anti-clockwise)

The fnction first calculates the size of an empty box, that is used to adjust the gap between letters by %10. Then the starting point is calculated using the parameters and the next letter is printed on that location in the given direction. Using the data of the letter size returned from the imagettftext call the angle is increased for the next iteration.

The function supports multibyte texts, as long as the font file has the necessary characters.

 

Disclaimer: This function is provided as is, without any warranties, expilict or otherwise. You are free to use this function in any work you do, commercial or open source. You are allowed to share this work on other sites provided that you display an open link to this page and give the necessary credit.

Author: Burhan BAVKIR



Share |

HomeHome