GD library font kerning word vs character in PHP

470 Views Asked by At

When i output a word with imagettftext() in PHP, the spacing, or rather kerning, between characters is different than when outputting single individual characters and advancing $x with the width of the character. The GD library seems to be using the kerning information from the font for character pairs.

$string = "Hello World, how do you do";

// write whole string
$box = imagettftext($im,$size,$angle,$x,$y,$black,$font,$string);

// write individual chars
for($i=0;$i<strlen($string);$i++){
  $char = substr($string,$i,1);
  $box = imagettftext($im,$size,$angle,$x,$y,$black,$font,$char);
  $x = abs($box[2])
}

word kerning vs character write

One work-around i'm using, is to get the width of character-pairs first,
an then subtract the width of the latter char.
e.g. width("He")-width("e), width("el")-width("l)

$both = imagettfbbox($size,0,$font,$char.$nextchar);
$next = imagettfbbox($size,0,$font,$nextchar);
$bothwidth = abs($both[4] - $both[0]);
$nextwidth = abs($next[4] - $next[0]);
$x += ($bothwidth - $nextwidth);

But even then, kerning is still somewhat different as when outputting the line.

Word output with overlay of calculated x for chars

  • What other ways exist to get kerning information from a font?
0

There are 0 best solutions below