safarov の関数には、私のユーザー ケースで実証された小さなバグが含まれています。$width より大きい単語を送信すると、その後すべての単語が改行されます。たとえば、次のようになります。
veryloooooooooooooongtextblablaOVERFLOWING
this
should
be
one
line
その理由は、imagettfbox が常に > $width になり、その「悪意のある」単語がテキスト内にあるためです。私の解決策は、各単語の幅を個別にチェックし、必要に応じて $width に収まるまで単語をカットすることでした (または、長さが 0 になった場合はカットをキャンセルします)。次に、通常のワードラッピングに進みます。結果は次のようになります。
veryloooooooooooooongtextblabla
this should be one line
変更された関数は次のとおりです。
function wrap($fontSize, $fontFace, $string, $width) {
$ret = "";
$arr = explode(" ", $string);
foreach ( $arr as $word ){
$testboxWord = imagettfbbox($fontSize, 0, $fontFace, $word);
// huge word larger than $width, we need to cut it internally until it fits the width
$len = strlen($word);
while ( $testboxWord[2] > $width && $len > 0) {
$word = substr($word, 0, $len);
$len--;
$testboxWord = imagettfbbox($fontSize, 0, $fontFace, $word);
}
$teststring = $ret.' '.$word;
$testboxString = imagettfbbox($fontSize, 0, $fontFace, $teststring);
if ( $testboxString[2] > $width ){
$ret.=($ret==""?"":"\n").$word;
} else {
$ret.=($ret==""?"":' ').$word;
}
}
return $ret;
}