Search code examples
phplaravel-5intervention

write a text with multiple fonts in PHP


I am currently using Intervention class to write a text on images.

writing is easily possible using text() method:

$img->text('The quick brown fox jumps over the lazy dog.', 120, 100);

Documentation

but my problem is that I want each character of a word with a different font. for example, imagine the word test, each character must use a different font. this is not easily possible since I can't find the position to start the next character, for instance in the word test, when I write t then when I want to call the text() method to write e, I don't know where should I set the position so the character e goes right after t.

How can I get the position of the last character so I can start writing the next character where the last one ends? or is there any other way to achieve this?


Solution

  • This is the method I use to get the width of a string.
    I use imagettftext(), so it may not suit you. But this code works.
    So if you have to choose between nothing and a code that works...

    $type_space = imagettfbbox($size, 0, $font, $text); // 0 = angle
    $text_width = abs($type_space[4] - $type_space[6]);
    

    imagettfbbox returns an array of values.
    http://php.net/manual/en/function.imagettfbbox.php

    Imagettfbbox() returns an array with 8 elements representing four points making the bounding box of the text:
    0 lower left corner, X position
    1 lower left corner, Y position
    2 lower right corner, X position
    3 lower right corner, Y position
    4 upper right corner, X position
    5 upper right corner, Y position
    6 upper left corner, X position
    7 upper left corner, Y position

    The code takes upper right x - upper left x which should mean width.