我正在尝试在图像上打印多行文本并居中对齐它们.
即
这是
一串文字
现在,我只有整个字符串的左侧位置.什么快捷方式让它工作?我认为它可能必须是整个字符串上的getttfbox,然后线上的爆炸中断,然后将新文本集中在更大的ttfbox中.这是屁股的痛苦......
编辑:想出一个解决方案:
foreach ( $strings as $index => $string ) {
$parts = explode ( "\n", $string['string'] );
if ( count ( $parts ) > 1 ) {
$bounds = imagettfbbox ( intval($string['fontsize']), 0, $font, $string['string'] );
$width = $bounds[2] - $bounds[0];
$height = $bounds[3] - $bounds[5];
$line_height = $height / count ( $parts );
foreach ( $parts as $index => $part ) {
$bounds = imagettfbbox ( intval($string['fontsize']), 0, $font, $part );
$new_width = $bounds[2] - $bounds[0];
$diff = ( $width - $new_width ) / 2;
$new_left = $string['left'] + $diff;
$new_string = $string;
$new_string['left'] = $new_left;
$new_string['top'] = $string['top'] + ($index * $line_height);
$new_string['string'] = $part;
$new_strings[] = $new_string;
}
}
}
if ( $new_strings )
$strings = $new_strings;
Run Code Online (Sandbox Code Playgroud)
在这种情况下,每个$ string都是一个数组,其中包含有关打印方式和内容的一些信息.希望能帮助别人.
您可以使用stil / gd-text类。免责声明:我是作者。
<?php
use GDText\Box;
use GDText\Color;
$img = imagecreatefromjpeg('image.jpg');
$textbox = new Box($img);
$textbox->setFontSize(12);
$textbox->setFontFace('arial.ttf');
$textbox->setFontColor(new Color(0, 0, 0));
$textbox->setBox(
50, // distance from left edge
50, // distance from top edge
200, // textbox width
100 // textbox height
);
// now we have to align the text horizontally and vertically inside the textbox
$textbox->setTextAlign('center', 'top');
// it accepts multiline text
$textbox->draw("This is\na string of text");
Run Code Online (Sandbox Code Playgroud)
示范:

这是一个将使用您提到的 imagettfbbox 的函数,我无法帮助自动换行,但也许正如您所建议的那样,提前分割字符串。
function imagettftext_cr(&$im, $size, $angle, $x, $y, $color, $fontfile, $text)
{
$bbox = imagettfbbox($size, $angle, $fontfile, $text);
$dx = ($bbox[2]-$bbox[0])/2.0 - ($bbox[2]-$bbox[4])/2.0;
$dy = ($bbox[3]-$bbox[1])/2.0 + ($bbox[7]-$bbox[1])/2.0;
$px = $x-$dx;
$py = $y-$dy;
return imagettftext($im, $size, $angle, $px, $py, $color, $fontfile, $text);
}
Run Code Online (Sandbox Code Playgroud)
编辑:还在 PHP 文档注释中发现了这一点...
这是一个将文本包装到图像中的简单函数。它会根据需要换行尽可能多的行,但 $angle 必须为零。$width 参数是图像的宽度。
function wrap($fontSize, $angle, $fontFace, $string, $width)
{
$ret = "";
$arr = explode(' ', $string);
foreach ( $arr as $word )
{
$teststring = $ret.' '.$word;
$testbox = imagettfbbox($fontSize, $angle, $fontFace, $teststring);
if ( $testbox[2] > $width ){
$ret.=($ret==""?"":"\n").$word;
} else {
$ret.=($ret==""?"":' ').$word;
}
}
return $ret;
}
Run Code Online (Sandbox Code Playgroud)