Page 1 of 1

[Resolved] GD Library - imagettfbbox() function help needed

Posted: Sun Apr 08, 2007 7:54 am
by kaisellgren
Hi,

I'm getting angry today I have spent too much time on this one for nothing :(

For some reason I get different $text_width for letters '9' and '8' :S

I've tried all these and actually all these code did the same - no difference:

Code: Select all

$image_data = imagettfbbox(8,0,$font,$highest.'0');
$text_width = max($text_data[2],$text_data[4])-min($text_data[0],$text_data[6]);

$image_data = imagettfbbox(8,0,$font,$highest.'0');
$text_width = abs($image_data[2]-$image_data[0]);

$image_data = imagettfbbox(8,0,$font,$highest.'0');
$text_width = abs($image_data[2])+abs($image_data[0]);
Does anyone have a solution for this? I need to get the width of the text to align my texts properly.
Now the texts are being offset by 0-3 pixels depending on the letters :S

Posted: Sun Apr 08, 2007 8:15 am
by feyd
Individual characters have varying widths, there's little you can do about that.

Posted: Sun Apr 08, 2007 9:58 am
by kaisellgren
Hmm.

When I have for instance numbers 900 and 800, it's shifting the 800 more left than the 900 :/

Do you have any ideas or let's say 'tricks' to get around this?

Hmm. Perhaps I could count the numbers with strlen() and then multiply it with static width of character 0 ? Yeah, I'll try that one :)

Posted: Sun Apr 08, 2007 4:02 pm
by feyd
If you want all the characters to fall into a specific grid position them based on the width of the w/m (case may matter here) .. I can't recall offhand, but one of them is used as a general width (because they're the widest characters in most instances.)

Posted: Mon Apr 09, 2007 3:40 am
by kaisellgren
Thanks for the tip.

I figured out the character widths.

upper case W is the widest character and lower case l (L) is the thickest character.

If someone else is (going to) have/having this same problem and found this thread, I better explain my solution:

1) Take the width of the widest character W:

Code: Select all

$image_data = imagettfbbox($font_size,$font_angle,$font,'W');
$text_width_base = abs($image_data[2]-$image_data[0]);
2) To get a width of string 'abcdefghjilkml' for instance, do this:

Code: Select all

$string = 'abcdefghijklm';
$text_width = strlen($string)*$text_width_base;