首页 文章

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

提问于
浏览
1

我使用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 repreptderit 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 .

输出图像是这样的:
enter image description here

我的代码是这样的:

<?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");
}
?>

我的代码中是否有任何错误,或者它是库中的错误?

1 回答

  • 1

    足够简单:注意 $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");
    }
    ?>
    

相关问题