Fully justify a line of text in C#

Previous examples such as Align lines of text in C# showed how to align text on the left, right, or center. The StringFormat class makes this relatively easy. Strangely the StringFormat class's alignment properties don't allow you to fully justify 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 is.

The method subtracts the total width of the words from the total available width to see how much space is available. It divides that amount by the number of spaces between 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 it drew plus the between word space.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.