【问题标题】:gd-text PHP library doesn't wrap text within boxgd-text PHP 库不将文本包装在框中
【发布时间】:2018-10-14 11:48:25
【问题描述】:

我正在使用gd-text PHP 库在图像上绘制文本

它可以工作,但如果我不提供空格,文本不会在我设置的边界框内换行,这是我的代码:

$textbox = new Box($img);
$textbox->setFontSize(20);
$textbox->setFontFace('arial.ttf');
$textbox->setFontColor(new Color(255,0,0));
$textbox->setBox(
   10,  // distance from left edge
   10,  // distance from top edge
   10, // textbox width
   10  // textbox height
);
$textbox->setTextAlign('center', 'top');
$textbox->draw("my text my text my text my text my text my text");

文本正确换行,但如果我不插入任何空格,则不会。文本一直在框外。该文档没有解释如何强制文本换行,即使没有空格存在

【问题讨论】:

    标签: php gd


    【解决方案1】:

    该库仅在空格处中断,但它非常简单,如果您的输入字符串没有空格,只要您超出框的宽度,我进行了更改就会中断。此更改仅适用于整行没有空格的情况。理想情况下,会有一种不会溢出的模式。这将很容易添加。您可能还想在单词中间出现中断时添加要插入的字符。

    Box 类中的 wrapTextWithOverflow 方法替换为:

    protected function wrapTextWithOverflow($text)
    {
        $lines = array();
        // Split text explicitly into lines by \n, \r\n and \r
        $explicitLines = preg_split('/\n|\r\n?/', $text);
        foreach ($explicitLines as $line) {
            // Check every line if it needs to be wrapped
            if((strpos($line, ' ')))
            {
                $words = explode(" ", $line);
                $line = $words[0];
    
                for ($i = 1; $i < count($words); $i++) {
                    $box = $this->calculateBox($line." ".$words[$i]);
                    if (($box[4]-$box[6]) >= $this->box['width']) {
                        $lines[] = $line;
                        $line = $words[$i];
                    } else {
                        $line .= " ".$words[$i];
                    }
                }
            }
            else
            {
                //If there are no spaces, append each character and create a new line when an overrun occurs
                $string = $line;
                $line = $string[0];
    
                for ($i = 1; $i < strlen($string); $i++) {
                    $box = $this->calculateBox($line.$string[$i]);
                    if (($box[4]-$box[6]) >= $this->box['width']) {
                        $lines[] = $line;
                        $line = $string[$i];
                    } else {
                        $line .= $string[$i];
                    }
                }
            }
    
            $lines[] = $line;
        }
        return $lines;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-07
      • 2016-05-14
      • 2020-09-10
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 2016-03-04
      相关资源
      最近更新 更多