You can use this method to break your text so that it'll fit a certain $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("can not make it fit");
}
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("infinite loop");
}
} while (!$fits);
}
$text = implode(PHP_EOL, $lines);
$drawText = new ImagickDraw();
$metrics = $im->queryFontMetrics($drawText, $text);
$metrics["text"] = $text;
assert('$metrics["textWidth"] <= $maxWidth');
return $metrics;
}
?>