Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get width of a single character from ttf-font in php?

I'm creating an dynamic image, which creates headers on my page using PHPs GD-library. The problem is, that I need a line-wrapping system. It's not a problem itself, but first I need to get the width (in pixels) of current character.

I'm pretty curious about this, is there any way? Or do I need to manually specify width of every abc?

Martti Laine

like image 659
Martti Laine Avatar asked Mar 19 '10 19:03

Martti Laine


1 Answers

You would have to do a imagettfbbox() on each single character.

Untested but should work:

$string = "Lorem Ipsum";
$size = 20;
$angle = 0;
$fontfile = "ARIAL.TTF";

$strlen = strlen($string);
for ($i = 0; $i < $strlen; $i++)
 {
    $dimensions = imagettfbbox($size, $angle, $fontfile, $string[$i]);
    echo "Width of ".$string[$i]." is ".$dimensions[2]."<br>";

 }
like image 172
Pekka Avatar answered Oct 12 '22 09:10

Pekka