我正在用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);
?>
发布于 2014-01-15 00:39:59
试试这个:
$text = 'Cool Stuff! this is nice LALALALALA LALA HEEH EHEHE';
$text = wordwrap($_POST['title'], 15, "\n");
发布于 2011-09-29 03:57:29
只需在空格上分解文本以获得单词数组,然后通过循环遍历单词数组开始构建行,通过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.=' ';
}
}
其中,竖线字符是换行符。
发布于 2019-07-07 12:19:39
如果你的字符串没有空格,你可以尝试这样做:
$text = 'Cool Stuff!thisisniceLALALALALALALAHEEHEHEHE';
$text = wordwrap($_POST['title'], 15, "\n",true); //TRUE = Wrap
https://stackoverflow.com/questions/6166261
复制相似问题