从边界框确定文本坐标a的正确方法是什么? [英] What is the correct way to determine text coordinates a from bounding box?

查看:82
本文介绍了从边界框确定文本坐标a的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出调用 imagettfbbox() 的结果,正确的像素是多少-完美点,提供给 imagettftext() ,这样文本就不会超出其边界框?

Given the result of a call to imagettfbbox(), what is the correct, pixel-perfect point to provide to imagettftext() such that the text will not extend beyond its bounding box?

我正在像这样从边界框确定基线的宽度/高度和x/y:

I am determining the width/height and x/y of the baseline from the bounding box like this:

$box = imagettfbbox($size, $angle, $font, $text);
$boxXCoords = array($box[0], $box[2], $box[4], $box[6]);
$boxYCoords = array($box[1], $box[3], $box[5], $box[7]);
$boxWidth = max($boxXCoords) - min($boxXCoords);
$boxHeight = max($boxYCoords) - min($boxYCoords);
$boxBaseX = abs(min($boxXCoords));
$boxBaseY = abs(min($boxYCoords));

然后我在边框框尺寸的图像上绘制一个填充的矩形:

I then draw a filled rectangle on my image of the dimensions of the bounding box:

imagefilledrectangle($image, 0, 0, $boxWidth - 1, $boxHeight - 1, $color);

然后,我绘制文本:

imagettftext($image, $size, $angle, $boxBaseX, $boxBaseY, $color, $font, $text);

但是,这导致文本超出矩形一两个像素.我已经在PHP的imagettfbbox()文档中看到过几次尝试解决此问题的尝试,但是它们都只是建议在此处和此处减去一两个像素,这对我来说似乎是一个技巧.这里发生了什么,为什么我们需要捏造数字以使事情变得正确?

However, this causes the text to extend beyond the rectangle by a pixel or two. I have seen several attempts to fix this issue on PHP's imagettfbbox() documentation, but they all just suggest substracting a pixel or two here and there, which seems like a hack to me. What's happening here, and why should we need to fudge the numbers to get things right?

推荐答案

我相信没有一种完美的方法可以根据imagettfbbox()返回的值以及使用非等距的.ttf在图像上放置具有单像素精度的文本.字体.在PHP手册上,许多用户已经发布了实现此目的的方法(带有或不带有数字的伪造).我建议在PHP手册上使用 jodybrabec的简单函数,它会计算出确切的边界框.我已经测试过这一点,并且仅在极端情况下,文本在一个方向上的位置最多错开1个像素.尽管如此,如果您在图像中添加一些填充(即使只是2或3像素),则文本将在100%的时间内处于图像尺寸之内.

I believe there is no perfect way to place text with single-pixel precision on an image based on what imagettfbbox() returns and also using .ttf non-monospaced fonts. Over at the PHP manual many users have posted ways to accomplish this (with and without fudging the numbers); I recommend using jodybrabec's simple function over at the PHP manual, which calculates the exact bounding box. I have tested this one and only in extreme cases is the text positioned at most 1 pixel off in one direction. Nonetheless, if you add some padding (even if it is just 2 or 3 pixels) to your image your text will be within the dimensions of the image 100% of the time.

这篇关于从边界框确定文本坐标a的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆