Armed with these six values, we can now calculate the correct
centering values. Because coordinates of the canvas have (0,0) in the
upper left corner, but ImagePSBText( ) wants the
lower left corner, the formula for finding $x and
$y isn't the same. For
$x, we take the difference between the size of the
canvas and the text. This gives the amount of whitespace that
surrounds the text. Then we divide that number by two, to find the
number of pixels we should leave to the left of the text. For
$y, we do the same, but add $yi
and $yr. By adding these numbers, we can find the
coordinate of the far side of the box, which is what is needed here
because of the inverted way the y coordinate is entered in GD.
We intentionally ignore the lower left coordinates in making these
calculations. Because the bulk of the text sits above the baseline,
adding the descending pixels into the centering algorithm actually
worsens the code; it appears off-center to the eye.
To center text, put it together like this:
function pc_ImagePSCenter($image, $text, $font, $size, $space = 0,
$tightness = 0, $angle = 0) {
// find the size of the image
$xi = ImageSX($image);
$yi = ImageSY($image);
// find the size of the text
list($xl, $yl, $xr, $yr) = ImagePSBBox($text, $font, $size,
$space, $tightness, $angle);
// compute centering
$x = intval(($xi - $xr) / 2);
$y = intval(($yi + $yr) / 2);
return array($x, $y);
}
$image = ImageCreate(500,500);
$text = 'PHP Cookbook Rules!';
$font = ImagePSLoadFont('/path/to/font.pfb');
$size = 20;
$black = ImageColorAllocate($image, 0, 0, 0);
$white = ImageColorAllocate($image, 255, 255, 255);
list($x, $y) = pc_ImagePSCenter($image, $text, $font, $size);
ImagePSText($image, $text, $font, $size, $white, $black, $x, $y);
ImagePSFreeFont($font);
header('Content-type: image/png');
ImagePng($image);
ImageDestroy($image);
// find the size of the text
list($xl, $yl, $xr, $yr) = ImagePSBBox($text, $font, $size,
$space, $tightness, $angle);
with these:
// find the size of the text
$box = ImageTTFBBox($size, $angle, $font, $text);
$xr = abs(max($box[2], $box[4]));
$yr = abs(max($box[5], $box[7]));
Here's an example of
pc_ImageTTFCenter() in use:
list($x, $y) = pc_ImageTTFCenter($image, $text, $font, $size);
ImageTTFText($image, $size, $angle, $x, $y, $white, $black,
'/path/to/font.ttf', $text);