Search code examples
c#textrotationdrawstring

Draw Rotated Text around it's center with RotateTransform


I have this code in C# to draw the rotated text

        Font font = new Font("Arial", 80, FontStyle.Bold);
        int nWidth = pictureBox1.Image.Width;
        int nHeight = pictureBox1.Image.Height;

        Graphics g = Graphics.FromImage(pictureBox1.Image);

        float w = nWidth / 2;
        float h = nHeight / 2;

        g.TranslateTransform(w, h);
        g.RotateTransform(90);

        PointF drawPoint = new PointF(w, h);
        g.DrawString("Hello world", font, Brushes.White, drawPoint);

        Image myImage=new Bitmap(pictureBox1.Image); 

        g.DrawImage(myImage, new Point(0, 0));

        pictureBox1.Image = myImage;
        pictureBox1.Refresh();

without rotate the text is drawn on the center of image, but with RotateTransform it goes half out of the image and the rotation center is way off.

How can I rotate the text only arount it's center ? without affecting the text position on the image.


Solution

  • If you want to draw rotated text at the center of the image, then offset the location of the text by half the measured size of the text:

    using (Font font = new Font("Arial", 80, FontStyle.Bold))
    using (Graphics g = Graphics.FromImage(pictureBox1.Image))
    {
        float w = pictureBox1.Image.Width / 2f;
        float h = pictureBox1.Image.Height / 2f;
    
        g.TranslateTransform(w, h);
        g.RotateTransform(90);
    
        SizeF size = g.MeasureString("Hello world", font);
        PointF drawPoint = new PointF(-size.Width / 2f, -size.Height / 2f);
        g.DrawString("Hello world", font, Brushes.White, drawPoint);
    }
    
    pictureBox1.Refresh();
    

    (It's a good idea to dispose of Font and Graphics objects when you're done with them, so I've added a couple using statements.)

    Variation #1: This snippet positions the upper-left corner of the text at (400, 200) and then rotates the text around that point:

    g.TranslateTransform(400, 200);
    g.RotateTransform(90);
    PointF drawPoint = new PointF(0, 0);
    g.DrawString("Hello world", font, Brushes.White, drawPoint);
    

    Variation #2: This snippet positions the upper-left corner of the text at (400, 200) and then rotates the text around the center of the text:

    SizeF size = g.MeasureString("Hello world", font);
    g.TranslateTransform(400 + size.Width / 2, 200 + size.Height / 2);
    g.RotateTransform(90);
    PointF drawPoint = new PointF(-size.Width / 2, -size.Height / 2);
    g.DrawString("Hello world", font, Brushes.White, drawPoint);