Use two different fonts in imagemagick on one line

前端 未结 2 1120
长情又很酷
长情又很酷 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:28

    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
    

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题