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

スペースでテキストを展開して単語の配列を取得し、words 配列をループして行の作成を開始し、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.=' ';
  }
}

パイプ文字は改行文字です。

于 2011-09-28T19:57:29.227 に答える