php - 使用 gd 在图像边界内换行文本

标签 php image gd truetype

我正在尝试将文本从数据库写入图像。文本有时包含很长的行,因此它无法在图像上显示为一行。

截至目前,我得到的输出为:http://prntscr.com/29l582

这是为此的代码:

$imageCreator = imagecreatefrompng($i+1 . ".png");
        $textColor = imagecolorallocate($imageCreator, 0, 0, 0);
        $textfromdb = $factformatted['fact'];
        $y = imagesy($imageCreator) - 228;
        $dimensions = imagettfbbox(20, 0, $fontname, $textfromdb);
        $x = ceil(($imageWidth - $dimensions[4]) / 2);
        imagettftext($imageCreator, 20, 0, $x, $y, $textColor, $fontname, $textfromdb);
        imagepng($imageCreator, "./fact".$i.".png");

有人可以帮我让它工作吗?

最佳答案

您可以使用 wordwrap函数和 explode函数截断多个字符串数组中的文本,然后打印它们:

$word = explode("\n", wordwrap ( "A funny string that I want to wrap", 10));

您获得此输出:

 array(5) {
  [0]=>
  string(7) "A funny"
  [1]=>
  string(6) "string"
  [2]=>
  string(6) "that I"
  [3]=>
  string(7) "want to"
  [4]=>
  string(4) "wrap"
}

你可以详细说明它(剪切文本,在不同的行上打印每个字符串,等等)。

示例(换行打印):

...
$dimensions = imagettfbbox(20, 0, $fontname, $textfromdb);
$y = imagesy($imageCreator) - 228;
$text = explode("\n", wordwrap($textfromdb, 20)); // <-- you can change this number
$delta_y = 0;
foreach($text as $line) {
    $delta_y =  $delta_y + $dimensions[3];
    imagettftext($imageCreator, 20, 0, 0, $y + $delta_y, $textColor, $fontname, $line);
}
...

垂直和水平居中:

...
$dimensions = imagettfbbox(20, 0, $fontname, $textfromdb);
$margin = 10;
$text = explode("\n", wordwrap($textfromdb, 20)); // <-- you can change this number
$delta_y = 0;
//Centering y
$y = (imagesy($imageCreator) - (($dimensions[1] - $dimensions[7]) + $margin)*count($text)) / 2;

foreach($text as $line) {
    $dimensions = imagettfbbox(20, 0, $fontname, $line);
    $delta_y =  $delta_y + ($dimensions[1] - $dimensions[7]) + $margin;
    //centering x:
    $x = imagesx($imageCreator) / 2 - ($dimensions[4] - $dimensions[6]) / 2;

    imagettftext($imageCreator, 20, 0, $x, $y + $delta_y, $textColor, $fontname, $line);
}
...

关于php - 使用 gd 在图像边界内换行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20453505/

相关文章:

javascript - 提交后ajax表单重定向

PHP从txt文件运行代码

html - @2x 视网膜图像不适用于 iOS7

CSS-2 背景图片和定位

PHP: 图像 ftbbox

PHP 检测源图像 url 链接是否指向 "broken"图像?

javascript - 如何从表单发送数据并将它们添加到现有的 POST 数据中,并在 PHP 中将它们连接到一个文本?

javascript - 在 For in 循环中渲染复选框并在 Vue JS 中绑定(bind)它们的值

css - 强制 img 元素填充容器的高度和宽度

php - 如何使用 PHP GD 显示动态生成的内联图像