在文本中使用空格字符时 imagettfbbox() 返回错误的尺寸
我正在从 PHP 动态创建一个图形菜单,它只会生成 1 个如下所示的图像:
One Two Three Four
然而问题是,我必须确定每个页面标题的 x 偏移量和宽度(例如,左侧偏移量和左侧偏移量) “One”的宽度(以像素为单位))以使用 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:不幸的是,当使用不同的字体大小和字体文件时,我一直得到错误的尺寸...
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种方法是使用 imagecolorat 函数来工作输出图像中特定点的像素颜色,它不会是最快的,甚至不一定是最好的方法,但它应该有效。
像这样的东西(搜索黑色像素)应该可以工作,并且会返回您正在寻找的边界,然后您可以根据需要将其转换为 x/ 坐标:
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:
实际上,它的真实边界可以从 imagettftext 函数的返回值计算出来。
Actually, its real bounds can be calculated from imagettftext function's return values.