PHP ImageMagick定位中心对齐的文本

问题描述 投票:1回答:1

我正在使用PHP ImageMagick(Imagick)创建由多个图像和文本组成的图像,这些图像和文本由我的网站的访问者上传和添加。实际上,它是一种画布,用户可以在其中上传图像,放置图像,选择添加一些文本,然后单击按钮,所有图像和文本都将被捆绑到一个图像中。

一切正常,但现在我想添加另一个功能:text-align:center。我希望我的用户能够添加居中对齐的文本。

要添加普通(左对齐)文本,请使用此代码:

$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在两者之间计算并且正确。当我左对齐文本时,结果如下:Input and output as they should be

但是,问题来了。我希望文本居中。因此,我将代码更改为:

$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));

文本确实居中,但位置不再正确。查看输入和输出结果:Strange positions when text is aligned in the center

之所以使用setGravity是因为我可以从左上方放置文本。但是现在看来,它又是从中间开始定位的,我不知道自己在做什么错。

$ new_left和$ new_top变量是正数,乘以一个正因子,因此x或y位置不可能为负。

有人有想法吗?

UPDATE:@MarkSetchell感谢您的答复,它使我朝着正确的方向前进。我没有完全按照您的意愿进行操作,但是通过在用户文本周围添加包装器(跨度)解决了该问题。我已经保存了图像的宽度和高度,因此很容易对文本进行处理。有了这些信息,我就可以确定文本的中心,然后从中心定位文本。这适用于水平定位:

$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);

但不是垂直放置。仍然不知道为什么,但是我现在就好像从顶部(而不是居中)定位一样处理它。然后添加一倍的文本的字体大小。我无法解释为什么这行得通,但是行得通。有人可以告诉我吗?

php imagemagick imagick
1个回答
0
投票

将高度设置为字体大小。像这样:

// Need to be defined: $conts, $col, $bg, $fs, $format, $w, $h, $dst, $font

$txt = new ImagickDraw();
$txt->setFillColor(new ImagickPixel($col));
$txt->setFontSize($fs);
$txt->setFont($font);
$txt->setTextAlignment(Imagick::ALIGN_CENTER);
$txt->annotation($w/2, $fs, $conts);  // Here

$im = new Imagick();
$im->newImage($w, $h, $bg, $format);
$im->drawImage($txt);
$im->writeImage($dst);
© www.soinside.com 2019 - 2024. All rights reserved.