Search code examples
c#textsystem.drawing

How do I print vertical text in C# that prints up? (StringFormat.DirectionVirtical prints down)


I want to print text in C# using System.Drawing, but setting the StringFormat.DirectionVirtical flag only seems to print text downward. I want it to print the other way, like you see in graphs.

This will be for more than just forms, so I want to see if there is a way to do this without using a transformation matrix while drawing.

Is there any way to accomplish this?


Solution

  • Use Graphics.RotateTransform to get the text rotate the way you want. For example:

    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }
        protected override void OnPaint(PaintEventArgs e) {
            string text = "Vertical text";
            SizeF textSize = e.Graphics.MeasureString(text, this.Font);
            e.Graphics.RotateTransform(-90);
            e.Graphics.DrawString(text, this.Font, Brushes.Black,
                new PointF(-textSize.Width, 0));
        }
    }