Using the imagettftext function with multiple lines? Anyone done this before?

后端 未结 4 937
时光说笑
时光说笑 2021-02-09 11:20

I\'m creating transparent text -> png images with php and so far so good. The only problem is that I want the ability to have the text word wrap due to a fixed width.. Or alter

4条回答
  •  终归单人心
    2021-02-09 11:47

    Of all the answers posted I liked Genius in trouble's the best but it just adds a linebreak every 15 characters rather than letting the text "flow" as it would in a modern word processor with variable line lengths depending on font choice & which characters are used (e.g. lowercase L takes less horizontal space than uppercase W--l vs. W).

    I came up with a solution which I've released as open source at https://github.com/andrewgjohnson/linebreaks4imagettftext

    To use you would simply change:

    $font = 'arial.ttf';
    $text = 'Cool Stuff! this is nice LALALALALA LALA HEEH EHEHE';
    $fontSize = 20;
    $bounds = imagettfbbox($fontSize, 0, $font, $text); 
    $width = abs($bounds[4]-$bounds[6]); 
    

    To:

    $font = 'arial.ttf';
    $text = 'Cool Stuff! this is nice LALALALALA LALA HEEH EHEHE';
    $fontSize = 20;
    $bounds = imagettfbbox($fontSize, 0, $font, $text); 
    $width = abs($bounds[4]-$bounds[6]);
    
    // new code to add the "\n" line break characters to $text
    require_once('linebreaks4imagettftext.php'); //https://raw.githubusercontent.com/andrewgjohnson/linebreaks4imagettftext/master/source/linebreaks4imagettftext.php
    $text = \andrewgjohnson\linebreaks4imagettftext($fontSize, 0, $font, $text, $width);
    

    Here is an example of the before & after with a longer piece of text:

提交回复
热议问题