Draw rotated text in C#

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

Positioning the rotated text is 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 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);
}

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

It 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 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;
// ... Code omitted ...
DrawRotatedTextAt(e.Graphics, -90, "December", x, y, the_font, Brushes.Red);
}
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

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.