PHP Imagick how to best fit text annotation

偶尔善良 提交于 2019-12-06 04:50:57

问题


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;

回答1:


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.

<?php

$bbox = imageftbbox(12, 0, 'Arial.ttf', 'This is a test');
$width_of_text = $bbox[2] - $bbox[0];

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.




回答2:


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.




回答3:


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.

$size = $MAX_FONT_SIZE;
while (true){
    $bbox = imageftbbox($size, 0, $font, $text );
    $width_of_text = $bbox[2] - $bbox[0];
    if ($width_of_text > $MAX_TEXT_WIDTH) {
            $size -= 1;
    }
    else {
            break;
    }
}
$height_of_text =  ($bbox[3] - $bbox[1]);
$draw->setFontSize( $size );
$image->annotateImage($draw, $TEXT_WIDTH_CENTER - $width_of_text/2, $TEXT_HEIGHT_CENTER - $height_of_text/2, 0, $text);


来源:https://stackoverflow.com/questions/7436815/php-imagick-how-to-best-fit-text-annotation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!