Skip to content

TextWrap

TextWrap draws multi‑line text inside a given box, automatically wrapping words and shrinking the font size so the whole block fits vertically. It supports alignment via Gravity and the same margin, padding, and border features as other drawable items.

public function __construct(
ImagickDraw $draw, // Text style: fill, font, font size (starting value), etc.
string $text, // The content to draw
int $initialFontSize = 60, // Starting font size for auto-fit
int $minFontSize = 10, // Minimum font size for auto-fit
Gravity $gravity = Gravity::TOP_LEFT // Text and block alignment
)
$draw = draw(fill: 'black');
$draw->setFont('DejaVu-Sans');
$drawBorder = draw(stroke: 'red', strokeWidth: 10);
$text = new TextWrap(
$draw,
'Hello World',
initialFontSize: 72,
minFontSize: 24,
gravity: Gravity::CENTER
);
// Optional spacing and border
$text->setMargin(10);
$text->setPadding(8);
$text->setBorder($drawBorder);
$text->setLetterSpacing(2);
$text->setWordSpacing(10);
$text->setLineSpacing(6);
// Draw onto image
$text->draw($imagick, $x, $y, $width, $height);

The text “Hello World” wrapped onto two lines to fit a narrow box, with margin, padding, and a red border

  • setLetterSpacing(float $spacing) adds extra space, in pixels, between characters (proxies ImagickDraw::setTextKerning()).
  • setWordSpacing(float $spacing) adds extra space, in pixels, between words (proxies ImagickDraw::setTextInterwordSpacing()).
  • setLineSpacing(int $spacing) adds extra space, in pixels, between wrapped lines, on top of the font metrics text height.
  • Wrapping is word‑based (splits on spaces); hyphenation and character‑level breaking are not implemented.
  • If the text still doesn’t fit at minFontSize, excess lines are not drawn (no ellipsis).
  • Explicit newlines in the input aren’t specially handled (the implementation splits by spaces). If you need manual breaks, consider splitting text and drawing multiple TextWrap blocks or extend the class.

The same text as a template:

{
"type": "text-wrap",
"text": "Hello World",
"fill": "black",
"font": "DejaVu-Sans",
"fontSize": 72,
"minFontSize": 24,
"gravity": "center",
"margin": 10,
"padding": 8,
"border": { "stroke": "red", "strokeWidth": 10 },
"letterSpacing": 2,
"wordSpacing": 10,
"lineSpacing": 6
}

llms.txt