PHP Imagick如何最适合文本注释
我正在将注释文本添加到 newPseudoImage 中,该图像工作正常,但我想让文本缩放以适应图像大小。
我有什么想法可以做到这一点吗?
$im = new Imagick();
$draw = new ImagickDraw();
$draw->setFillColor($color);
$draw->setFont($font);
$draw->setFontSize(($width, $height) / 100) * 15);
$draw->setGravity(Imagick::GRAVITY_CENTER);
$im->newPseudoImage($width, $height, "canvas:{$bg}");
$im->annotateImage($draw, 0, 0, 0, $text);
$draw->clear();
$draw->destroy();
$im->setImageFormat('gif');
header("Content-Type: image/gif");
echo $im;
I'm adding annotation text to a newPseudoImage which works fine but I'd like to make the text scale to fit the image size.
Any ideas how I might do this?
$im = new Imagick();
$draw = new ImagickDraw();
$draw->setFillColor($color);
$draw->setFont($font);
$draw->setFontSize(($width, $height) / 100) * 15);
$draw->setGravity(Imagick::GRAVITY_CENTER);
$im->newPseudoImage($width, $height, "canvas:{$bg}");
$im->annotateImage($draw, 0, 0, 0, $text);
$draw->clear();
$draw->destroy();
$im->setImageFormat('gif');
header("Content-Type: image/gif");
echo $im;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为您可以使用 imageftbbox 函数来帮助您。
这将为您提供文本字符串的边界框,具有给定的 ttf 字体、大小和角度。
只要文本没有正确适合图像,您就可以创建一个循环来增大或减小字体大小。
您可以查看
$width_of_text
并调整字体大小,只要字体未按您的喜好缩放即可。请记住,随着字体的增加,宽度和高度也会增加。根据您尝试将其扩展到的范围可能会有所帮助。
I think you could use the imageftbbox function to help you out.
This will give you the bounding box for a text string, with the given ttf font, size, and angle.
You could create a loop to increase or decrease the font size as long as the text is not fitting the image properly.
You could look at the
$width_of_text
and adjust the font size as long as the font isn't scaled to your liking. Keep in mind, as you increase the font, the width and height will grow.Depending on what you are trying to scale it to that may help.
我面临着同样的问题,虽然我还没有尝试过这个,因为我远离我的机器,但我会尝试一下。
使用该类的查询字体度量函数,我将能够获得文本的计算宽度,然后将其与其容器的指定宽度进行比较。我将调整字体大小并重复,直到足够接近。通过这种方式,您可以获得相当准确的结果,但请记住,如果图像中有多个文本项,可能会出现性能问题。
另一方面,如果您不太关心文本样式,则可以使用标题。
I'm facing the same issue and although I've not tried this yet as I'm away from my machine, I'm going to give this a go.
Using the query font metrics function of the class I will be able to get the calculated width of the text and then compare it with the specified width of its container. I'll make adjustments to the font size and repeat until its near enough. You could get it quite accurate this way but bare in mind possible performance issues if you have multiple text items in the image.
On the other hand, if you weren't concerned about styling the text as much you could use caption.
这是一个有点幼稚的解决方案(我可以使用二分搜索来找到合适的字体大小),但它对我有用。
在我的示例中,我想将文本放置在图像中的框上,因此我使用 imageftbbox 计算正确的字体大小。
This is a slightly naive solution (I could have used binary search to find the proper font size) , but it works for me.
In my example I want to place text on a box in the image, so I calculate the proper font size with imageftbbox.