How to: Rotating text 90 degrees in GDI+

You can use the StringFormatFlags.DirectionVertical in the DrawString command to rotate text.  Unfortunately, when drawing the graph it draws the text mirror-imaged the wrong way.  So much for StringFormat.

In order to rotate text 90 degrees,  you'll need to draw the text to a separate bitmap in memory and then draw the resulting image to the screen.

In your paint event handler code add the following:

SizeF labelSize = g.MeasureString(myLabel, GraphFont);

Bitmap stringmap = new Bitmap((int)labelSize.Height + 1, (int)labelSize.Width + 1);

Graphics gbitmap = Graphics.FromImage(stringmap);

gbitmap.SmoothingMode = SmoothingMode.AntiAlias;

// g.DrawString(m_LabelY, GraphFont, Brushes.Blue, new PointF(ClientRectangle.Left , ClientRectangle.Top + 100), theFormat);

gbitmap.TranslateTransform(0, labelSize.Width);

gbitmap.RotateTransform(-90);

gbitmap.DrawString(myLabel, GraphFont, Brushes.Blue, new PointF(0 , 0), new StringFormat());

g.DrawImage(stringmap, (float)ClientRectangle.Left, (float)ClientRectangle.Top + 100);

And don't forget to dispose of your bitmap and graphics objects at the end of onpaint

gbitmap.Dispose();
stringmap.Dispose();

Ebook Download
View all
Learn
View all