使用gd在图像边界内包裹文本行 [英] Wrap lines of text within image boundaries using gd

查看:120
本文介绍了使用gd在图像边界内包裹文本行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write text from a db to images. The text some times contains lengthy lines so that it does't fit in one line on image.

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

As of now I am getting the output as: 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");

有人可以帮助我让它运作吗?

Can someone help me to make it work?

推荐答案

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

You can use the wordwrap function and the explode function to truncate the text in multiple arrays of string, then print them:

$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"
}

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

Than you can elaborate it (cutting the text, print each string on different lines, etc...).

示例(在新行上打印):

Example (printing on new lines):

...
$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);
}
...

这篇关于使用gd在图像边界内包裹文本行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆