Wrap lines of text within image boundaries using gd

后端 未结 1 1062
长发绾君心
长发绾君心 2021-01-03 08:08

I am trying to write text from a db to images. The text some times contains lengthy lines so that it does\'t fit in one line on image.

As of now I am getting the out

1条回答
  •  攒了一身酷
    2021-01-03 08:45

    You can use the wordwrap function and the explode function to truncate the text in multiple arrays of string, then print them:

    $word = explode("\n", wordwrap ( "A funny string that I want to wrap", 10));
    

    You obtain this output:

     array(5) {
      [0]=>
      string(7) "A funny"
      [1]=>
      string(6) "string"
      [2]=>
      string(6) "that I"
      [3]=>
      string(7) "want to"
      [4]=>
      string(4) "wrap"
    }
    

    Than you can elaborate it (cutting the text, print each string on different lines, etc...).

    Example (printing on new lines):

    ...
    $dimensions = imagettfbbox(20, 0, $fontname, $textfromdb);
    $y = imagesy($imageCreator) - 228;
    $text = explode("\n", wordwrap($textfromdb, 20)); // <-- you can change this number
    $delta_y = 0;
    foreach($text as $line) {
        $delta_y =  $delta_y + $dimensions[3];
        imagettftext($imageCreator, 20, 0, 0, $y + $delta_y, $textColor, $fontname, $line);
    }
    ...
    

    To center both vertical and horizontal:

    ...
    $dimensions = imagettfbbox(20, 0, $fontname, $textfromdb);
    $margin = 10;
    $text = explode("\n", wordwrap($textfromdb, 20)); // <-- you can change this number
    $delta_y = 0;
    //Centering y
    $y = (imagesy($imageCreator) - (($dimensions[1] - $dimensions[7]) + $margin)*count($text)) / 2;
    
    foreach($text as $line) {
        $dimensions = imagettfbbox(20, 0, $fontname, $line);
        $delta_y =  $delta_y + ($dimensions[1] - $dimensions[7]) + $margin;
        //centering x:
        $x = imagesx($imageCreator) / 2 - ($dimensions[4] - $dimensions[6]) / 2;
    
        imagettftext($imageCreator, 20, 0, $x, $y + $delta_y, $textColor, $fontname, $line);
    }
    ...
    

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