如何使用 PHP Imagick 根据框大小对齐文本?

How to align text based on its box size using PHP Imagick?

我在图像中的特定位置 X 和 Y 放置了一些文本。我还尝试像在 Photoshop 中的框中那样对齐文本,但是当我使用 $draw->setTextAlignment() 时,我得到了不同的结果。见下文:

当前结果:

想要的结果:

文本及其属性(字体名称、大小、颜色等)是动态的,因此大小可以变化。

有人可以帮我吗?

代码:

<?php

$draw = new \ImagickDraw();
$draw->setStrokeColor(new \ImagickPixel('black'));
$draw->setFillColor(new \ImagickPixel('red'));
$draw->setStrokeWidth(1);
$draw->setFontSize(36);

// First box
$draw->setTextAlignment(\Imagick::ALIGN_LEFT);
$draw->annotation(250, 75, "First line\nSecond Line");

// Second box
$draw->setTextAlignment(\Imagick::ALIGN_CENTER);
$draw->annotation(250, 210, "First line\nSecond Line");

// Third box
$draw->setTextAlignment(\Imagick::ALIGN_RIGHT);
$draw->annotation(250, 330, "First line\nSecond Line");

$draw->line(250, 0, 250, 500);

$image = new \Imagick();
$image->newImage(500, 500, new \ImagickPixel('transparent'));
$image->setImageFormat("png");
$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();

p.s。这些示例中使用的垂直线仅用于显示对齐差异。

我找到了解决方案!查看结果图片和说明:

我们可以使用 Imagick::queryFontMetrics 查询 $draw 对象以了解文本的宽度和高度 - 它还 returns 此目的不需要其他信息,请参阅:

X 坐标ImagickDraw::annotation 的第一个参数,指定文本在图像水平轴上的绘制位置。

根据我们手中的文本宽度 (textWidth),我们可以计算出文本的正确 X 坐标,对每个文本对齐执行以下操作:

  • - 按原样使用 X 坐标 - 无事可做。
  • 居中 - 求和 X 坐标 + 文本的半宽。
  • - 求和 X 坐标 + 文本的整个宽度。

查看实际代码:

<?php
$image = new \Imagick();

$draw = new \ImagickDraw();
$draw->setStrokeColor(new \ImagickPixel('black'));
$draw->setFillColor(new \ImagickPixel('red'));
$draw->setStrokeWidth(1);
$draw->setFontSize(36);
$text = "First line\nSecond Line";

// First box
$draw->setTextAlignment(\Imagick::ALIGN_LEFT);
$draw->annotation(250, 75, $text);

// Second box
$draw->setTextAlignment(\Imagick::ALIGN_CENTER);
$metrics = $image->queryFontMetrics($draw, $text);
$draw->annotation(250 + ($metrics['textWidth'] / 2), 210, $text);


// Third box
$draw->setTextAlignment(\Imagick::ALIGN_RIGHT);
$metrics = $image->queryFontMetrics($draw, $text);
$draw->annotation(250 + ($metrics['textWidth']), 330, $text);

$draw->line(250, 0, 250, 500);

$image->newImage(500, 500, new \ImagickPixel('transparent'));
$image->setImageFormat("png");
$image->drawImage($draw);

header("Content-Type: image/png");
echo $image->getImageBlob();

它输出文本正确对齐的图像。

有关详细信息,请参阅以下参考资料: