自动换行代码在随机点剪切文本

Word wrap code cuts the text at a random point

我使用 PHP 和 GD 库制作了一个代码,该代码接收一个字符串作为输入并将其分成几行,以便它可以放入图像中。问题是,根据我输入的文本,它会停在一个随机点。例如,使用以下文本作为输入:

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

输出图像是这样的:

我的代码是这样的:

<?php
function createStory($content){
    $text = $content;
    $jpg_image = imagecreatefromjpeg('imagebuilder/footage/story1.jpg');
    $white = imagecolorallocate($jpg_image, 255, 255, 255);
    $font_path = 'Arial.ttf';
    $words = explode(" ",$text);
    $proccessedtext = "";
    $line = "";
    $line .= $words[0] . " ";
    for($i = 1; $i < count($words); $i++){
        $bbox = imagettfbbox(25, 0, $font_path, $line);
        $width = $bbox[4]-$bbox[0];
        if($width<700){
            $line .= $words[$i] . " ";
        }else{
            $proccessedtext .= $line . " \n".$words[$i]. " ";
            $line = "";
        }
    }
    imagettftext($jpg_image, 25, 0, 75, 600, $white, $font_path, $proccessedtext);
    imagejpeg($jpg_image, "imagebuilder/created/readyStory.jpg");
    imagedestroy($jpg_image);
    return("/imagebuilder/created/readyStory.jpg");
}
?>

我的代码有什么错误还是库中的错误?

很简单:请注意,在您超过最大宽度之前,$processedText 不会收到 $line 的内容!因此,在任何给定时间,它只会收到整行加上一个溢出的单词。因此,如果您的剩余文本没有超过当前行一个额外的单词,那么还有剩余部分仍需要处理。尝试在 for 循环之后直接添加 $processedText .= $line;

<?php
function createStory($content){
    $text = $content;
    $jpg_image = imagecreatefromjpeg('imagebuilder/footage/story1.jpg');
    $white = imagecolorallocate($jpg_image, 255, 255, 255);
    $font_path = 'Arial.ttf';
    $words = explode(" ",$text);
    $proccessedtext = "";
    $line = "";
    $line .= $words[0] . " ";
    for($i = 1; $i < count($words); $i++){
        $bbox = imagettfbbox(25, 0, $font_path, $line);
        $width = $bbox[4]-$bbox[0];
        if($width<700){
            $line .= $words[$i] . " ";
        }else{
            $proccessedtext .= $line . " \n".$words[$i]. " ";
            $line = "";
        }
    }
    $processedText .= $line;
    imagettftext($jpg_image, 25, 0, 75, 600, $white, $font_path, $proccessedtext);
    imagejpeg($jpg_image, "imagebuilder/created/readyStory.jpg");
    imagedestroy($jpg_image);
    return("/imagebuilder/created/readyStory.jpg");
}
?>