使用带有多行的imagettftext函数?有人这样做过吗?

ion*_*ish 6 php png text imagettftext

我用php创建透明文本 - > png图像,到目前为止一直很好.唯一的问题是我希望能够通过固定的宽度来进行文本自动换行.或者也可以在文本中插入断行符.有没有人有任何exp这样做?这是我的代码......

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


?>
Run Code Online (Sandbox Code Playgroud)

Gen*_*ble 18

试试这个

$text = 'Cool Stuff! this is nice LALALALALA LALA HEEH EHEHE';
$text = wordwrap($_POST['title'], 15, "\n");
Run Code Online (Sandbox Code Playgroud)

我希望它对其他人有所帮助,因为我认为对你来说太晚了...

  • 今天帮助了我.2年后... :-) (3认同)
  • 这对我今天有所帮助,谢谢! (2认同)

小智 6

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

像这样的东西:

$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.=' ';
  }
}
Run Code Online (Sandbox Code Playgroud)

管道字符是换行符.

  • 当行变得太长时,只需添加PHP_EOL而不是遍历行,就像这样:`if($ lineWidth <$ maxLineWidth){$ newText.= $ value.''; } else {$ newText.= PHP_EOL.$值; }` (2认同)