UI Text: Wrap and Expand to keep aspect ratio

As I see it there are two options to display text within a background image:

  1. Resize the background image to fit the text size (Content size fitter on the text)
  2. Keep the background image constant size, and have the text wrap to fit the width

I’m trying to combine the two - expand the background as much as necessary to fit the entire text, but also wrap the text so that the aspect ratio of the background image remains constant.

Any tools that do this, or any ideas on how to do it?

Edit: Here’s an example of larger text and shorter text.


I’d like the algorithm to be able to match the background and text sizes to both these cases, without having to manully insert "
" in the text or manually sizing the rect. The point is to wrap the text, and automatically resize the component so that the text fills it as much as possible, leaving no empty space above/below.

TextGenerator textGen = new TextGenerator();
TextGenerationSettings generationSettings = textCompo.GetGenerationSettings(textCompo.rectTransform.rect.size);
float width = textGen.GetPreferredWidth(text, generationSettings);
if (width > preferedWidthMax)
layoutElement.preferredWidth = preferedWidthMax;
This is the most elegant way I’ve found to this problem. Note that the text’s parent has a content size fitter and a layout group components, and the text itself has a layout element.

Check the other related question:


Take a look at Unity - Scripting API: TextGenerator.

You’ll need to iteratively generate text to determine the proper size for layout. If you have particular aspect ratio (such as phi) you might start small and add vertical height a line at a time (query the font for the line height), calculating the width along the way until the bounds are large enough to contain the text without truncation.