views:

131

answers:

0

Hi,

I'm creating a graphical menu dynamically from PHP, it results in only 1 image that looks like this:

One    Two    Three    Four

The problem however is, that I have to determine the x-offset and the width of each page title (e.g. the left offset and the width of "One" in pixels) to position the image with css.

All works fine, except for page titles that contain spaces - imagettfbbox() returns the wrong positions. I am using an arial font (TTF)

Any suggestions on how I get around this issue?

Edit: I got it working now, using the following function to determine the text's bounds:

function calculateTextBox($font_size, $font_angle, $font_file, $text) {
    $box = imagettfbbox($font_size, $font_angle, $font_file, $text);

    $min_x = min(array($box[0], $box[2], $box[4], $box[6]));
    $max_x = max(array($box[0], $box[2], $box[4], $box[6]));
    $min_y = min(array($box[1], $box[3], $box[5], $box[7]));
    $max_y = max(array($box[1], $box[3], $box[5], $box[7]));

    return array(
        'left' => ($min_x >= -1) ? -abs($min_x + 1) : abs($min_x + 2),
        'top' => abs($min_y),
        'width' => $max_x - $min_x,
        'height' => $max_y - $min_y,
        'box' => $box
    );
}

Edit 2: Unfortunately I keep getting wrong dimensions when using different font sizes and font files...