Use two different fonts in imagemagick on one line

前端 未结 2 1139
长情又很酷
长情又很酷 2021-01-07 09:16

So i want to draw on my image text lets say in this example \"Trevor, 24\"

But I want to use the font Helvetica for Trevor, and for 24 i want to use the font Arial.

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-07 09:31

    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.

提交回复
热议问题