Align lines of text in C#

The example Draw a paragraph one line at a time in C# shows how to draw the lines of a paragraph one at a time. Once you can do that, it's a simple matter to align the lines on the left, right, or center.

This example uses the following enumeration to let the code specify an alignment. (This example doesn't use the predefined HorizontalAlignment enumeration because in a later example I'll add another value.)

// Text justification.
public enum TextJustification

Now the program's text drawing methods pass a new parameter named "justification" that indicates how the text should be aligned. The biggest change is in the DrawLine method that actually draws each line of text.

// Draw a line of text.
private void DrawLine(Graphics gr, string line, Font font,
    Brush brush, float x, float y, float width,
    TextJustification justification)
    // Make a rectangle to hold the text.
    RectangleF rect = new RectangleF(x, y, width, font.Height);

    // Make a StringFormat to align the text.
    using (StringFormat sf = new StringFormat())
        // Use the appropriate alignment.
        switch (justification)
            case TextJustification.Left:
                sf.Alignment = StringAlignment.Near;
            case TextJustification.Right:
                sf.Alignment = StringAlignment.Far;
            case TextJustification.Center:
                sf.Alignment = StringAlignment.Center;

        gr.DrawString(line, font, brush, rect, sf);

This method uses a switch statement to see which kind of justification it should use. It then sets a StringFormat object's Alignment property to the appropriate value to align the text. It finishes by calling the Graphics object's DrawString method to draw the text.

(Note that this example draws the text one line at a time and you probably don't really need to do that. You could pass the DrawString method the whole paragraph of text and let it draw it within the desired rectangle. This example draws the text one line at a time to get ready for later examples where that technique is important.)



What did you think of this article?

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

Submitted comments are subject to moderation before being displayed.


 Email (will not be published)


Your comment is 0 characters limited to 3000 characters.