Search code examples
phpgd

Annoying whitespace to the left when using the GD Library and text


I'm working on a class, which can create a number of text inputs and position them on top of each other so that they align, left and right - like this:

3 lines
(source: vandret.dk)

The problem is that sometimes, the text is not positioned correctly. When drawing A's, it works. When drawing M's (and a number of other letters with a vertical stroke - P's, I's etc) it puts a whitespace to the left and cropping the sentence to the right. If you look at the two lines below, they should align up perfectly - but doesn't.

3 lines
(source: vandret.dk)

3 lines
(source: vandret.dk)

If you right-click and view the images directly, the problem will be more obvious.

It works like this:

  1. Create an empty canvas, put the text on it "virtually" to measure the width and height
  2. When the dimensions are obtained, create a canvas that matches the dimensions of the text. We now have a stage, like 800 pixels in width
  3. Downsize the sentence or word to fit 400 pixels in width
  4. Increase the y-offset for another sentence or word
  5. Do the same thing all over again, as long as we have sentences/words to display

My starting point was this and I built this code:

$fontsize = 120;
$size = imagettfbbox($fontsize, 0, "./fonts/".$fontname, $text);
$xsize = abs($size[0]) + abs($size[2]);
$ysize = abs($size[5]) + abs($size[1]);
//print_r($size);
$image = imagecreate($xsize, $ysize);   

// Colors
$backgroundcolor = imagecolorallocate($image, 255, 255, 255);
$textcolor = imagecolorallocate($image, 155, 142, 138);

imagettftext($image, $fontsize, 0, 0, abs($size[5]), $textcolor, "./fonts/".$fontname, $text);
header("content-type: image/png");
imagepng($image);

and then, all of the resizing stuff, which works. But why is the text aligned wrong?


Solution

  • Solved! It's a font problem, not a GD problem. I opened the TrueType-font inside High-Logic FontCreator and found out that several of the letters have a spacer to the left.

    I used a function in the program called "Automatic Metrics Wizard" to strip all of the characters of the left indentation, which was done in a matter of seconds - and the font still looks acceptable. The kerning on letters like j looks a bit off - but it will do.