Align text by lines in C#

[align text]

The example Draw paragraphs 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 text one line at a time 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 alignment value.)

// Text justification.
public enum TextJustification

Now the program’s text drawing methods pass a new parameter justification that indicates how the text should be aligned. The biggest change is in the following DrawLine method that 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.)

Download Example   Follow me on Twitter   RSS feed   Donate

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

One Response to Align text by lines in C#

  1. Pingback: Justify paragraphs in C# - C# HelperC# Helper

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.