Purrx

Shrink text to fit any box

Fit text into any box by stepping the font size down until the wrapped lines fit, without splitting words, and report text that can't fit at all.

11 min+30 XPHands-on

Here's the situation that breaks naive slide generators. The model asks for a 42pt title, and the layout puts it in a column one fifth of the slide wide. At 42pt the words don't fit. We can't make the box bigger, because the other columns need their space. So the text has to get smaller: .

Both titles asked for 42pt. In the narrow column the engine stepped down until every word fit whole and the lines fit the height: 30pt. With room to spare, 42pt stays 42pt.

The loop

Try sizes from the requested size downwards, one point at a time. At each size:

  • Wrap the text to the box's width and measure the height with textHeight.
  • Check that every word fits on a line by itself. Otherwise "factories" becomes "factori" and "es", which no reader accepts.
  • If both are true, this is the biggest size that works. Return it with the lines.

When nothing fits

Sometimes even the minimum size can't fit: a whole paragraph in a tiny box. Then return the minimum size anyway, with overflow: true. The text still appears (overflowing its box) and the engine reports a problem. In module 7, those problems go back to the model, which shortens the text.

Under the hood — Stepping by one point is slow, isn't it?

From 42pt down to 10pt is at most 33 tries, each a wrap of a short string: well under a millisecond. It's also easy to read and obviously correct. The production engine uses a binary search over half-point steps because it fits thousands of text boxes per deck, but the idea is the same: bigger sizes never fit where a smaller one doesn't, so you can search.

Key takeaways

  • Start at the requested size and step down until the wrapped text fits the box.
  • Don't accept a size where a single word is wider than the box: shrink further instead.
  • If nothing fits even at the minimum size, draw it anyway and report the overflow.

Sign in to run the exercise

Reading is free. Writing code here needs an account so we have somewhere to keep your Gemini key and the +30 XP you are about to earn.