Evenly spaced true type fonts in PHP GD

Okay so as promised in my earlier blog post. Here is the trick to print true type fonts in PHP GD with even spacing between characters.

Let me give you some background info about the issue and how I came across it.

I was developing charts for one of my client and as the charting script was also custom coded by me I had no where to go other then solve the issue myself.

The scenario was that the numbers printing in the chart on Y axis were like 1010, 1070, 980, 995, etc.

My charting algo was taking values [a lots of them lets say 5000 points] and creating a line chart from it. It was also taking min and max values and then dividing it by number of labels that I wanted on Y axis.

Everything was smooth until the client noticed that the numbers which were printing one below the other were slight off.

1010
1070
980
995

Like above it was printing on Y axis but 9 wasn’t coming exactly under 1 and the next number 8 wasn’t coming exactly under 0 and so on.

I searched a lot about evenly spacing out the true type fonts in PHP GD but nothing came in my hands.

There were loads of articles about how to print evenly spaced true type fonts in PHP GD with other PHP functions and all blah.

But as always it was slight common sense and looking at the things from different point of view.

Here is what I did.

I took each and every value that was being printed in the loop as Y axis into a string variable.

Checked its length. Looped through each character/number in the Value and printed them at the spacing of 5 pixels each.

Below is the code to help you if you are in similar situation sometime.

<?php
settype($Value, “string”);
$len = strlen($Value);
$len = $len – 1;
$x = 0;
$space = 0;
for ( $x == 0; $x <= $len; $x++ )
{
$NewVal = $Value[$x];
imagettftext($Picture,$FontSize,0,$TextWidth + $space,$YPos,$TextColor,$FontName,$NewVal);
$space = $space + 5;
}
?>

I hope that helps. If any questions then shoot me an email from my contact page.