Use two different fonts in imagemagick on one line

眉间皱痕 提交于 2019-12-01 01:08:19

This is easy, but you'll have to do a bit of work. Use Imagick::queryFontMetrics to track the drawing width of each typeface, and simply offset to X coordinate to ensure alignment is uniformed.

// 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'];
}

Of course the above example can be simplified & reduced.

You could look at using Pango with ImageMagick. I know it works at the command line but have never tried with the PHP binding...

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!