Imagick annotateImage: how to set text position fr

2019-08-10 12:26发布

I'm trying to create a wrapper function around annotateImage to be able to set the exact top and left positions of a given text. The default method sets the y-position from the baseline, which means there has to be a lot of experimentation involved if one wants to draw a text at an exact spot on an image. This is what I mean...

$image->annotateImage($draw, 0, 0, 0, 'The quick brown fox');

In the above code, the text is invisible because the y position is 0. So to fix this, I've started with the following function where I add an offset of 40 to y...

function addText($image, $draw, $x, $y, $text) {
  $y = $y + 40;
  $image->annotateImage($draw, $x, $y, 0, $text);
}

addText($image, $draw, 0, 0, 'The quick brown fox'); // draw at 0, 0

But it's not very reliable because it doesn't take into account any factors such as font size, etc...

What's the best way to achieve this?

1条回答
相关推荐>>
2楼-- · 2019-08-10 12:52

I've found a solution that works well. If the gravity is set to 'NorthWest', the text tends to keep its x y position from the top left.

$draw->setGravity(Imagick::GRAVITY_NORTHWEST);
$image->annotateImage($draw, 0, 0, 0, 'The quick brown fox');
查看更多
登录 后发表回答