[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Draw rotated text in C#

Drawing rotated text isn't hard in C#. Simply apply a RotateTransform to a Graphics object and draw the text using DrawString.

Positioning the rotated text is a bit harder. The transformation rotates the position of the text so getting it to appear where you want it can be confusing.

A much simpler approach is to draw the text at the origin and use a translation transformation to move the text where you want it. The following DrawRotatedTextAt function does this.

// Draw a rotated string at a particular position. private void DrawRotatedTextAt(Graphics gr, float angle, string txt, int x, int y, Font the_font, Brush the_brush) { // Save the graphics state. GraphicsState state = gr.Save(); gr.ResetTransform(); // Rotate. gr.RotateTransform(angle); // Translate to desired position. Be sure to append // the rotation so it occurs after the rotation. gr.TranslateTransform(x, y, MatrixOrder.Append); // Draw the text at the origin. gr.DrawString(txt, the_font, the_brush, 0, 0); // Restore the graphics state. gr.Restore(state); }

This method first saves the Graphics object's state so it doesn't lose any other transformations that may be in effect. It then resets the transform to remove any other effects.

The code then applies a rotation transformation followed by a translation to position the text as desired. It uses DrawString to draw the text at the origin and the transformation moves it to the desired location. Finally the code restores the saved graphical state to put the Graphics object back the way it was.

The main program uses the following code to display rotated text. Only the first couple of entries are shown to save space.

private void Form1_Paint(object sender, PaintEventArgs e) { e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; using (Font the_font = new Font("Comic Sans MS", 20)) { const int dx = 50; int x = 20, y = 150; DrawRotatedTextAt(e.Graphics, -90, "January", x, y, the_font, Brushes.Red); x += dx; DrawRotatedTextAt(e.Graphics, -90, "February", x, y, the_font, Brushes.Red); x += dx; DrawRotatedTextAt(e.Graphics, -90, "March", x, y, the_font, Brushes.Red); ... } }

Download the example to experiment with it and to see additional details.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.