BLOG.CSHARPHELPER.COM: Draw text left justified, right justified, or centered in C#
Draw text left justified, right justified, or centered in C#
The StringFormat class has Alignment and LineAlignment properties that let you specify how you want text aligned vertically and horizontally. Alignment determines the text's horizontal alignment and LineAlignment determines its vertical alignment.
You can set these properties to one of the values defined by the StringAlignment enumeration. Those values are Near, Far, and Center.
Near aligns the text close to the top or left edge of the drawing area depending on whether you're setting Alignment or LineAlignment. Far aligns the text close to the right or bottom edge of the drawing area. As you can probably guess, Center centers the text.
This example's DrawText method, which is shown in the following code, draws some sample text with a specified Alignment in an indicated rectangle.
The code draws the rectangle so you can see where it is drawing. It then creates a StringFormat object. (Because the StringFormat class implements IDisposable, the code should call its Dispose method when it is done with the object. The using statement shown here automatically calls Dispose when the code exits the using block so the code doesn't need to remember to do it.)
The code sets the StringFormat's Alignment property. It then sets FormatFlags to LineLimit so the text doesn't end with a line that is truncated vertically. (See the example Use the StringFormat class's string format flags in C#.) It also sets the Trimming property so lines of text end at word boundaries rather than displaying part of a word or character at the end. (See the example Use the StringFormat class's line trimming values in C#.)
Finally the code calls the Graphics object's DrawString method to draw the sample text.
The main program uses the following code to draw three samples of text showing each of the Alignment values.
// Left alignment. Rectangle rect = new Rectangle(gap, gap, wid, hgt); e.Graphics.DrawRectangle(Pens.Blue, rect); DrawText(e.Graphics, text, rect, StringAlignment.Near);
Unfortunately the Alignment property doesn't support full justification where the word spacing is adjusted to make the text completely fill each line (except the last one in the paragraph). I'll probably write something to do that soon.
Comments