Justified Text



Justified Text

With Delphi – in fact with the Windows GDI, which the VCL wraps – you can easily print out text that is left-or right-justified or centered. But have you ever tried drawing fully justified text, where both the left and right edges adhere to the bounding rectangle?

This unit provides a method for drawing justified text, works around problems/bugs using Windows GDI methods, and provides extra functionality not found when using the GDI implementation.

Left: normal, left-justified text with three paragraphs.
Center: justified text using this unit, with default formatting options.
Right: justified text using this unit and turning on options to justify trailing paragraph lines, and justify single words.

The JustifiedDrawText unit

The unit contains a single externally accessible method, DrawTextJustified(). Use it similarly to DrawText() or DrawTextEx(). It allows you to specify a canvas, a rectangle, and a number of options, and the end result is fully-justified text on the canvas.

The options are:

The first, tjJustifyTrailingLines, justifies the final trailing lines of a paragraph; by default they are left-aligned. The second, tjJustifySingleWords, does the same for lines that consist of a single word, stretching the word out to fit the justification width. The third, tjMeasureOnly, adjusts the bottom of the passed-in Rect to the size the text would take if it were printed. It is similar to using DrawText with DT_CALCRECT. The fourth, tjForceManual, is not necessary to pass. Internally the code switches between the Windows API method and a custom justification method in a number of situations. Passing this option forces it to always use the custom justification method and never use the Windows API method.

The code uses a combination of inbuilt GDI routines and, where they are buggy – this includes when using important fonts, such as Segoe UI, the default font on Vista and Windows 7 – or where they do not have the required functionality, the code uses a custom justification routine. This behaviour is automatically chosen so that you will always get correct results.

It’s free and licensed under the commercial-friendly MPL.

Discussions about this page on Google+