Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php imagettftext letter spacing

Does anybody have a function that draws a ttf string (imagettftext) with specified letter spacing?

I cannot find any build-in GD function so I think that it should be done letter by letter adding some constant width.

Maybe someone have such function already :)

ps. the best font will be arial.ttf

like image 231
radzi0_0 Avatar asked Aug 03 '11 12:08

radzi0_0


2 Answers

function imagettftextSp($image, $size, $angle, $x, $y, $color, $font, $text, $spacing = 0)
{        
    if ($spacing == 0)
    {
        imagettftext($image, $size, $angle, $x, $y, $color, $font, $text);
    }
    else
    {
        $temp_x = $x;
        for ($i = 0; $i < strlen($text); $i++)
        {
            $bbox = imagettftext($image, $size, $angle, $temp_x, $y, $color, $font, $text[$i]);
            $temp_x += $spacing + ($bbox[2] - $bbox[0]);
        }
    }
}

and the call:

imagettftextSp($image, 30, 0, 30, 30, $black, 'arial.ttf', $text, 23);

Function parameters order meets standard imagettftext parameters order, and the last parameter is optional $spacing parameter. If not set or the passed value is 0, the kerning / letter spacing is not set.

like image 198
radzi0_0 Avatar answered Sep 17 '22 09:09

radzi0_0


I know this was answered a while back, but I needed a solution that had letter spacing and maintained the angular offsets.

I modified radzi's code to accomplish this:

function imagettftextSp($image, $size, $angle, $x, $y, $color, $font, $text, $spacing = 0)
{        
    if ($spacing == 0)
    {
        imagettftext($image, $size, $angle, $x, $y, $color, $font, $text);
    }
    else
    {
        $temp_x = $x;
        $temp_y = $y;
        for ($i = 0; $i < strlen($text); $i++)
        {
            imagettftext($image, $size, $angle, $temp_x, $temp_y, $color, $font, $text[$i]);
            $bbox = imagettfbbox($size, 0, $font, $text[$i]);
            $temp_x += cos(deg2rad($angle)) * ($spacing + ($bbox[2] - $bbox[0]));
            $temp_y -= sin(deg2rad($angle)) * ($spacing + ($bbox[2] - $bbox[0]));
        }
    }
}
like image 30
Pidalia Avatar answered Sep 20 '22 09:09

Pidalia