8

我正在用php创建透明文本-> png图像,到目前为止一切都很好。唯一的问题是我希望能够由于固定宽度而使文本自动换行。或者能够在文本中插入断线。有没有人有任何经验这样做?这是我的代码...

<?php

$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]); 
$height = abs($bounds[7]-$bounds[1]); 



$im = imagecreatetruecolor($width, $height);
imagealphablending($im, false);
imagesavealpha($im, true);


$trans = imagecolorallocatealpha($im, 255, 255, 255, 127);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);


imagecolortransparent($im, $black);
imagefilledrectangle($im, 0, 0, $width, $height, $trans);


// Add the text
imagettftext($im, $fontSize, 0, 0, $fontSize-1, $grey, $font, $text);


imagepng($im, "image.png");
imagedestroy($im);


?>
4

4 回答 4

20

尝试这个:

$text = 'Cool Stuff! this is nice LALALALALA LALA HEEH EHEHE';
$text = wordwrap($_POST['title'], 15, "\n");
于 2014-01-14T16:39:59.047 回答
6

只需在空格上展开文本以获得单词数组,然后通过遍历单词数组开始构建行,通过 imagettfbbox 测试每个新单词的添加,看看它是否创建了超过您设置的 maxwidth 的宽度。如果是这样,请在新的一行开始下一个单词。我发现简单地创建一个添加了特殊换行符的新字符串更容易,然后再次分解该字符串以创建一个行数组,每个行都将分别写入最终图像。

像这样的东西:

$words = explode(" ",$text);
$wnum = count($words);
$line = '';
$text='';
for($i=0; $i<$wnum; $i++){
  $line .= $words[$i];
  $dimensions = imagettfbbox($font_size, 0, $font_file, $line);
  $lineWidth = $dimensions[2] - $dimensions[0];
  if ($lineWidth > $maxwidth) {
    $text.=($text != '' ? '|'.$words[$i].' ' : $words[$i].' ');
    $line = $words[$i].' ';
  }
  else {
    $text.=$words[$i].' ';
    $line.=' ';
  }
}

其中管道字符是换行符。

于 2011-09-28T19:57:29.227 回答
2

在所有发布的答案中,我最喜欢Genius in trouble最好的,但它只是每 15 个字符添加一个换行符,而不是让文本“流动”,因为它在具有可变行长的现代文字处理器中,具体取决于字体选择和哪些字符使用(例如,小写 L 占用的水平空间比大写 W--l vs. W 少)。

我想出了一个解决方案,我已在https://github.com/andrewgjohnson/linebreaks4imagettftext作为开源发布

要使用,您只需更改:

$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]); 

至:

$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);

这是一个带有较长文本的之前和之后的示例:

例子

于 2018-06-04T00:13:27.217 回答
-2

如果你的字符串没有任何空格,你可以试试这个:

 $text = 'Cool Stuff!thisisniceLALALALALALALAHEEHEHEHE';
 $text = wordwrap($_POST['title'], 15, "\n",true); //TRUE = Wrap
于 2019-07-07T04:19:39.317 回答