Fully justify a line of text in C#

Fully justify a line of text

The StringFormat class makes it fairly easy to left justify, right justify, or center a line of text, but strangely it doesn’t provide a method to fully justify a line of text (so it extends all the way to both the left and right margins.

This example uses the following code to draw a single line of fully justified text.

// Draw justified text on the Graphics object
// in the indicated Rectangle.
private void DrawJustifiedLine(Graphics gr, RectangleF rect,
    Font font, Brush brush, string text)
    // Break the text into words.
    string[] words = text.Split(' ');

    // Add a space to each word and get their lengths.
    float[] word_width = new float[words.Length];
    float total_width = 0;
    for (int i = 0; i < words.Length; i++)
        // See how wide this word is.
        SizeF size = gr.MeasureString(words[i], font);
        word_width[i] = size.Width;
        total_width += word_width[i];

    // Get the additional spacing between words.
    float extra_space = rect.Width - total_width;
    int num_spaces = words.Length - 1;
    if (words.Length > 1) extra_space /= num_spaces;

    // Draw the words.
    float x = rect.Left;
    float y = rect.Top;
    for (int i = 0; i < words.Length; i++)
        // Draw the word.
        gr.DrawString(words[i], font, brush, x, y);

        // Move right to draw the next word.
        x += word_width[i] + extra_space;

This method breaks the line of text into words. It then loops through the words and uses the Graphics object’s MeasureString method to see how wide each word will be when drawn in the indicated font.

The method subtracts the total width of the words from the total available width to see how much space is left over. It divides that amount by the number of spaces between the words to determine how much space it should leave between each pair of words to make the text fill the desired area.

Finally, the method loops through the words again. It draws each word and then increases the X coordinate for the next word by the width of the word plus the extra between-word space.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in fonts, graphics, printing, strings and tagged , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *