Rich text - the justification calculation
Photo by Esperanza Doronila / Unsplash

Rich text - the justification calculation

If you are laying out text then you will need to justify it. But what's the algorithm? Lets take a look...

This is a short article about one of the features needed for text layout. The prerequisites are that you have measured the characters in the line and have their type (spaces vs letters) and widths.

What is Justification?

It is used on every newspaper you have ever read - those tidy columns of text where the words line up perfectly with the edges? That's line justification!

Think about laying out the words on the line line one after the other with spaces in between. When you get to a word that would go beyond the available width you stop - that word will be on the next line. So now you have a sequence of words and spaces and some additional space after the last word.

Line justification chops off this trailing space then distributes its space by adding padding to the spaces between the words so that the leftmost and rightmost words are lined up with the left and right line ends respectively.

Lets take that apart:

  • line is made up of words,
  • those words are either composed entirely from one or more spaces - call these space words - or of other characters - call these letter words.
  • remove the space words at the start and end of the line, if any.
  • the mission now is to expand all space characters so that the words fill the line completely.
  • This is justification!

The calculation

We therefore need to know how much additional space to add. The formula for this is

  • spaceCharCnt = the number of space chars in all the remaining space words
  • spaceWordWidth = the width of all space words combined
  • letterWordWidth - the width of all non-space words combined
  • lineWidth = the width available on the line
  •  gap = (lineWidth - letterWordWidth - spaceWordWidth) - this is the width that we have to share out to the space characters
  • spaceCharWidthExtra = gap / spaceCharCnt: this is the width to be added to each space char.

Then loop through the words of the line. Each space char gets the spaceCharWidthExtra added, and we manage the left position for each word based on the accumulated affect.

Summary

Being able to justify text on a line is a high quality feature but the process and the math are simple as we have seen.

Thanks for reading.

VW Jan 2025