你可以使用此方法来分割你的文本,使其适合特定的 $maxWidth。
<?php
protected function _fitText($text, $maxWidth)
{
$im = new Imagick();
$im->newImage($this->_width, $this->_height, "none");
$lines = explode(PHP_EOL, trim($text));
$DEBUG_LOOP = 0;
for ($k = 0; $k < count($lines); ++$k) {
do {
$drawText = new ImagickDraw();
$metrics = $im->queryFontMetrics($drawText, $lines[$k]);
$fits = $metrics["textWidth"] <= $maxWidth;
if ($fits) {
break;
}
$pos = mb_strrpos($lines[$k], " ");
if ($pos === false) {
throw new RuntimeException("无法使其适合");
}
if (!isset($lines[$k + 1])) {
$lines[$k + 1] = null;
}
$lines[$k + 1] = trim(mb_substr($lines[$k], $pos + 1) . " " . $lines[$k + 1]);
$lines[$k] = trim(mb_substr($lines[$k], 0, $pos));
if (++$DEBUG_LOOP >= 200) {
throw new RuntimeException("无限循环");
}
} while (!$fits);
}
$text = implode(PHP_EOL, $lines);
$drawText = new ImagickDraw();
$metrics = $im->queryFontMetrics($drawText, $text);
$metrics["text"] = $text;
assert('$metrics["textWidth"] <= $maxWidth');
return $metrics;
}
?>