【问题标题】:wrap and center text in gd and php在 gd 和 php 中换行和居中文本
【发布时间】:2011-02-17 20:54:43
【问题描述】:

我有一行文本需要在 GD 图像中换行和居中。我也在使用 ttf 字体。有什么可以给我一些帮助吗?

我已经设法得到一些文本来包装做以下事情,但现在我需要把它放在中心:

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;
}

【问题讨论】:

    标签: php text image-processing formatting gd


    【解决方案1】:

    用户 valentijn de Pagter 在 php net manual 上提供了一个很好的函数来计算框(我看到你确实在使用 imagettfbbox())并从返回的数组中计算如何使文本居中。你可以在这里找到它:

    center text with imagettfbbox

    【讨论】:

      【解决方案2】:

      水平和垂直居中:从整个文本的 imagettfbbox 中获取一半高度(带有新行),然后从图像的一半高度中减去它 ($start_x)。

      现在用新行分割文本,为每一行创建 ttfbox 并获取它的高度 ($h) 和半宽度 ($w)。从图像的一半宽度+$w$start_x开始画线,将$h添加到$start_x,重复直到写完所有行。

      【讨论】:

        【解决方案3】:

        这就是我所做的。使用 imagettftext 函数,您可以添加新的行标记并继续到下一行。您可以在一定数量的字符后将 \n 添加到字符串中。此示例只会在空格处中断,因此单词不会被截断。

                    $description=$property['description'];
                    $len=strlen($description);
                    $str="";
                    $c=0;
                    for($i=0;$i<$len;$i++){
                        $chr=substr($description,$i,1);
                        $str.=$chr;
                        if($c>40 && $chr==" ") {
                            $str.="\n";
                            $c=0;   
                        }
                        $c++;
                        }
                    $result=$str;
                    imagettftext($img, 15, 0, $x - 60, $descmgn, $textcolor, $font, $result);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-05-20
          • 2013-02-07
          • 1970-01-01
          • 2011-04-10
          • 2016-11-16
          • 2011-02-26
          • 2021-11-07
          相关资源
          最近更新 更多