Use a StringFormat object and a Rectangle to align painted text in C#

This example's Paint event handler draws nine strings inside a rectangle aligned vertically and horizontally in the nine possible combinations: top/left, top/center, bottom/right, etc.

The StringFormat object's LineAlignment property determines how the text is aligned vertically. It can take the values Near (top), Center (middle), or Far (bottom).

The Alignment property determines how the text is aligned horizontally. It can take the same values Near (left), Center (middle), or Far (right).

The following code shows how the program draws its text aligned in the upper left corner. To draw the rest of the text, the program uses different Alignment and LineAlignment values.

// Top.
sf.LineAlignment = StringAlignment.Near; // Top.

// Top/Left.
sf.Alignment = StringAlignment.Near; // Left.
e.Graphics.DrawString("Top/Left", font, Brushes.Black, rect, sf);

   

 

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.