## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# 15.5. Drawing Centered Text

## Problem

You want to draw text in the center of an image.

## Solution

Find the size of the image and the bounding box of the text. Using those coordinates, compute the correct spot to draw the text.

For built-in GD fonts, use the `pc_ImageStringCenter( )` function shown in Example 15-1.

Example 15-1. pc_ImageStringCenter( )

```function pc_ImageStringCenter(\$image, \$text, \$font) {

// font sizes
\$width  = array(1 => 5, 6, 7, 8, 9);
\$height = array(1 => 6, 8, 13, 15, 15);

// find the size of the image
\$xi = ImageSX(\$image);
\$yi = ImageSY(\$image);

// find the size of the text
\$xr = \$width[\$font] * strlen(\$text);
\$yr = \$height[\$font];

// compute centering
\$x = intval((\$xi - \$xr) / 2);
\$y = intval((\$yi - \$yr) / 2);

return array(\$x, \$y);
}```

For example:

```list(\$x, \$y) = pc_ImageStringCenter(\$image, \$text, \$font);
ImageString(\$image, \$font, \$x, \$y, \$text, \$fore);```

For PostScript fonts, use the `pc_ImagePSCenter( )` function shown in Example 15-2.

Example 15-2. pc_ImagePSCenter( )

```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);
}```

For example:

`list(\$x, \$y) = pc_ImagePSCenter(\$image, \$text, \$font, \$size); ImagePSText(\$image, \$text, \$font, ...`

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required