【问题标题】:Wrap lines of text within image boundaries using gd使用 gd 在图像边界内换行文本
【发布时间】:2013-12-25 13:14:43
【问题描述】:

我正在尝试将文本从数据库写入图像。文本有时包含很长的行,因此它不适合图像上的一行。

截至目前,我得到的输出为: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");

有人可以帮我解决吗?

【问题讨论】:

  • 你到底想怎么适应这个?插入换行符?更改字体大小等?
  • 我更喜欢换行,但是如果字符串实际上比图像宽度大,那么就必须减小字体大小!
  • 检查this 讨论,了解通过利用imagettfbbox() 函数以最大允许文本宽度(以像素为单位) 换行的可能方法

标签: php image gd truetype


【解决方案1】:

您可以使用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);
}
...

【讨论】:

  • 现在是这样的:prntscr.com/2btaek 我会尝试自己修复它,但由于我是新手,因此我们将不胜感激。我正在尝试将其垂直和水平居中。
  • 我把答案改成了文字居中,看看。我无法测试,但它应该可以工作......
  • 我做了这个并且它对齐了 y 部分:pastie.org/private/ryutguudjnk7sjp5afsbdw。但是您的 $x 部分给了我空白图像。我认为文字将朝向图像的外部! :( 当我检查 x x:-841.5 的值时
  • 这对我有用! pastie.org/private/fg6d1ky4spfzaufivxvwjw 无论如何感谢您的帮助伙伴。我会接受你的作为接受的答案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-28
  • 2014-05-20
  • 2017-04-27
相关资源
最近更新 更多