BLOG.CSHARPHELPER.COM: Easily draw rotated text on a form in C#
Easily draw rotated text on a form in C#
The example Draw rotated text in C# shows how to draw rotated text. Unfortunately that method requires you to use code at run time to position the text. It's not too hard but it's inconvenient if you're trying to draw rotated text on a form.
This example lets you use Label controls to determine where rotated text is positioned. At design time, add Labels to the form to indicate where the text should be placed. You can set AutoSize = False and BorderStyle = FixedSingle for the Labels to make them easier to position.
The following DrawSidewaysText method draws rotated text inside a given Rectangle. It uses a StringFormat to determine how the text is arranged within the Rectangle.
// Draw sideways text in the indicated rectangle.
private void DrawSidewaysText(Graphics gr, Font font, Brush brush, Rectangle bounds, StringFormat string_format, string txt)
{
// Make a rotated rectangle at the origin.
Rectangle rotated_bounds = new Rectangle(
0, 0, bounds.Height, bounds.Width);
// Rotate.
gr.ResetTransform();
gr.RotateTransform(-90);
// Translate to move the rectangle to the correct position.
gr.TranslateTransform(bounds.Left, bounds.Bottom, System.Drawing.Drawing2D.MatrixOrder.Append);
// Draw the text.
gr.DrawString(txt, font, brush, rotated_bounds, string_format);
}
The method first creates a new Rectangle with the same dimensions as the original one rotated 90 degrees and with its upper left corner at the origin (0, 0).
The code resets the Graphics object's transformation and rotates it by -90 degrees. It then adds a translation to move the now rotated rectangle to its desired final position (where the bounds Rectangle is).
Finally the code draws the text in the rotated Rectangle and using the StringFormat. The result is the text is drawn in the rotated Rectangle, rotated by -90 degrees so it's sideways, and then translated to the desired destination.
When the example program starts, it uses the following code to hide the Labels that position the rotated text.
// Hide the labels that position the rotated text.
private void Form1_Load(object sender, EventArgs e)
{
lblRotated1.Visible = false;
lblRotated2.Visible = false;
lblRotated3.Visible = false;
}
The example program uses the following Paint event handler to draw the rotated text.
This code creates a StringFormat that centers text and sets the Graphics object's TextRenderingHint property to AntiAliasGridFit to produce a nice result. It then calls the DrawSidewaysText method to display three rotated strings. It uses the positioning Labels' Bounds properties to determine where the rotated text is drawn.
Comments