0

我正在从 PHP 动态创建一个图形菜单,它只产生一个看起来像这样的图像:

One    Two    Three    Four

然而问题是,我必须确定每个页面标题的 x 偏移量和宽度(例如,左偏移量和“一”的宽度(以像素为单位))才能使用 css 定位图像。

一切正常,除了包含空格的页面标题 - imagettfbbox() 返回错误的位置。我正在使用 arial 字体 (TTF)

关于我如何解决这个问题的任何建议?

编辑:我现在开始工作了,使用以下函数来确定文本的边界:

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

编辑 2:不幸的是,当我使用不同的字体大小和字体文件时,我总是得到错误的尺寸......

4

2 回答 2

0

One way to do it would be to use the imagecolorat function to work out the colour of a pixel at particular point in the image, its not going to be the quickest or even necessarily the best way to do it but it should work.

Something like this (searching for black pixels) should work, and will return the bounds you're looking for which you can then translate into x/ co-ordinates if you want:

function get_bounds($image)
{
    $height = imagesy($image);
    $width = imagesx($image);


    $to_return = new stdClass();
    $to_return->top = null;
    $to_return->bottom = null;
    $to_return->left = null;
    $to_return->right = null;

    for ($x = 0; $x < $width; $x++)
    {
        for ($y = 0; $y < $height; $y++)
        {
            $color = imagecolorat($image, $x, $y);
            $rgb = imagecolorsforindex($image, $color);

            // If its black
            if (($rgb['red'] == 0) && ($rgb['green'] == 0) && ($rgb['blue'] == 0))
            {
                if (($y < $to_return->top) || is_null($to_return->top))
                {
                    $to_return->top = $y;
                }

                if (($y > $to_return->bottom) || is_null($to_return->bottom))
                {
                    $to_return->bottom = $y;
                }

                if (($x < $to_return->left) || is_null($to_return->left))
                {
                    $to_return->left = $x;
                }

                if (($x > $to_return->right) || is_null($to_return->right))
                {
                    $to_return->right = $x;
                }
            }
        }
    }

    return $to_return;
}
于 2014-05-09T10:05:12.963 回答
0

实际上,它的实际边界可以从 imagettftext函数的返回值中计算出来。

于 2020-06-05T05:09:49.593 回答