I'm working with PHP to create png images on the fly. I am having trouble centering multiple lines of text though. I have been using the following code to get the centered x coordinate for the $name variable.

//get font width for name
$font_width = ImageFontWidth(15);
$image_width = ImageSX($im);
$length = $font_width * strlen($name);
$image_center_x = ($image_width/2)-($length/2);

But I can't seem to get it to work for multiple lines of text. The first line is centered perfectly but the next line is not. Any ideas on how to get this to work?

Thanks alot!
Sung

    The variable $image_center_x contains the x value of where to start printing a line of text whose length is $length. Are you recalculating for each line?

      Yeah - I was recalculating for each line - but for some reason it would always plug in a value that wouldn't center perfectly. I went searching around though on how to use imagettfbbox and found a pretty good piece of code that centers text perfectly. It goes:

      $box = imagettfbbox ($namefontsize, 0, 'Lsans.TTF', $name);
      $tw=$box[2]-$box[0]; //image width
      // x position
      $px = (imagesx($im) -$tw)/2;

      I'm repeating the code for each line I'm printing out (except I add a 1,2,3,etc to the variables). I'm not the most experienced coder though and I'm wondering if their is a better way to recalculate for each line than simply performing the script for each line. I'm thinking this is the only way though as the $string variable is different for each line of text.

      Thanks for replying to my post though.
      Sung

        Write a Reply...