【问题标题】:Use two different fonts in imagemagick on one line在一行中使用 imagemagick 中的两种不同字体
【发布时间】:2016-01-11 23:35:19
【问题描述】:

所以我想在我的图像文本上绘制让我们在这个例子中说“Trevor,24”

但我想为 Trevor 使用 Helvetica 字体,而对于 24,我想使用 Arial 字体。但我希望它在同一条线上,看起来就像是一条线。

是否有可能或者我将如何制作它,以便即使我改变名字和年龄,我也可以像这样打印出来?

“特雷弗,(Helvetica) 24(Ariel)”

我假设将它们彼此相邻打印,但如果有人输入的名称比 Trevor 24 长,就会忽略它。

想法是让它在同一行

你们觉得呢?

$draw = new ImagickDraw();
$color = new ImagickPixel('#5b5b5b');
$bgcolor = new ImagickPixel('none');
$font = 'Helvetica';
//$draw->setFont($font);
//$draw->setFontSize(39);
$draw->setFillColor($color);
$draw->setStrokeAntialias(true);
$draw->setTextAntialias(true);

$draw->setFont($font);
$draw->setFontSize(39);

$text = 'Trevor, 24';

$draw->setGravity(Imagick::GRAVITY_WEST);
$image->annotateImage($draw, 50, 241, 0, $text);

【问题讨论】:

  • 您必须创建两个单独的文本并一个一个应用字体。

标签: php imagemagick imagick imagemagick-convert


【解决方案1】:

这很容易,但您需要做一些工作。使用Imagick::queryFontMetrics跟踪每个字体的绘制宽度,并简单地偏移到X坐标以确保对齐一致。

// Let's create a generator to simplify context management (YMMV)
function context_generator() {
    $text = array('Trevor (Helventica)',' 24 (Impact)');
    $font = array('Helvetica', 'Impact');
    foreach($text as $k => $v ) yield [$font[$k], $v];
}
$image = new Imagick();
$image->newImage(450, 100, "steelblue", "png");
$draw = new ImagickDraw();
$draw->setFillColor('black');
$draw->setStrokeAntialias(true);
$draw->setTextAntialias(true);
$draw->setFontSize(24);
$x = $y = 40;
foreach(context_generator() as $attr) {
    // Set context typeface
    $draw->setFont($attr[0]);
    // Calculate how big this type face will be (and any validation to protect overflow)
    $metrics = $image->queryFontMetrics($draw, $attr[1], FALSE);
    // Draw part
    $image->annotateImage($draw, $x, $y, 0, $attr[1]);
    // Offset origin X
    $x += $metrics['textWidth'];
}

上面的例子当然可以简化和简化。

【讨论】:

  • 这正是我来这里之前正在做的事情。基本上测量文本的长度,然后添加其余部分,这很棒。
【解决方案2】:

您可以考虑将 Pango 与 ImageMagick 结合使用。我知道它可以在命令行上运行,但从未尝试过使用 PHP 绑定...

convert \
     pango:'<span font="Times 48" foreground="white" background="blue">Trevor</span><span font="Arial 32" foreground="yellow" background="black">24</span>' \
     pango.png

【讨论】:

  • Pango 代表在这种情况下是最好的。
猜你喜欢
  • 2011-11-16
  • 2014-06-30
  • 2016-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
相关资源
最近更新 更多