I am using PHP ImageMagick (Imagick) for creating images consisting of multiple images and texts, uploaded and added by visitors of my website. It's actually a kind of canvas where a user can upload their images, position them, optionally add some text and after a click on the button, all the images and texts will be bundled to one image.
Everything works fine, but right now I want to add another feature: text-align: center. I want my user to be abled to add text aligned in the center.
For adding normal (left aligned) text is use this code:
$text_temp = new ImagickDraw();
$text_temp->setGravity(Imagick::GRAVITY_NORTHWEST);
...
$image->annotateImage($text_temp, $new_left, $new_top, $angle, html_entity_decode($item->text));
$new_left, $new_top, $angle are calculated in between and are correct. When I left align the text, this are the results: Input and output as they should be
But, here comes the problem. I want the text to be centered. So I changed my code to this:
$text_temp = new ImagickDraw();
if($item->textalign == 'center') {
$text_temp->setGravity(Imagick::GRAVITY_NORTHWEST);
$text_temp->setTextAlignment(Imagick::ALIGN_CENTER);
}
...
$image->annotateImage($text_temp, $new_left, $new_top, $angle, html_entity_decode($item->text));
The text is indeed centered, but the position is not correct anymore. See the input and output results: Strange positions when text is aligned in the center
The reason I use setGravity is because I can position the text from the top left. But right now it looks like it's positioning from the center again and I have no idea what I'm doing wrong.
The $new_left and $new_top variables are positive numbers, multiplied by a positive factor, so there is no way the x- or the y-positions are negative.
Does anyone have an idea?
UPDATE: @MarkSetchell Thanks for your reply, it putted me in the right direction. I didn't do it exactly like you, but I fixed the problem by adding a wrapper (span) around the user text. I already saved the width and height of images, so it was easy to do the same with texts. With these information I can determine the center of the text, and thus position it from center. This worked for horizontal positioning:
$text_temp->setTextAlignment(Imagick::ALIGN_CENTER);
$new_left = $new_left + ($new_width / 2);
//$new_top = $new_top + ($new_height / 2);
$new_top = $new_top + ($new_fontsize);
But it didn't for vertical positioning. Still don't know why, but I handle it now as if I position from top (not center). Then add one time the font size of the text. I can't explain why this is working, but it works. Can somebody tell me?