9

I'm using the the drawstring method of Graphics class to draw a String on Image.

  g.DrawString(mytext, font, brush, 0, 0);

I'm trying to rotate the text by angle using the Rotate Transform Function of the graphic object so that the text can be drawn at any angle.How can i do it using Rotate Transform. The rotate Transform Code i used is

    Bitmap m = new Bitmap(pictureBox1.Image);
    Graphics x=Graphics.FromImage(m);
    x.RotateTransform(30);
    SolidBrush brush = new SolidBrush(Color.Red);
    x.DrawString("hi", font,brush,image.Width/2,image.Height/2);
//image=picturebox1.image
    pictureBox1.Image = m;

The Text is Drawn at a rotated angle but it is not drawn at the centre as i want.Plz help me out.

techno
  • 6,100
  • 16
  • 86
  • 192

2 Answers2

27

It's not enough to just RotateTransform or TranslateTranform if you want to center the text. You need to offset the starting point of the text, too, by measuring it:

Bitmap bmp = new Bitmap(pictureBox1.Image);
using (Graphics g = Graphics.FromImage(bmp)) {
  g.TranslateTransform(bmp.Width / 2, bmp.Height / 2);
  g.RotateTransform(30);
  SizeF textSize = g.MeasureString("hi", font);
  g.DrawString("hi", font, Brushes.Red, -(textSize.Width / 2), -(textSize.Height / 2));
}

From How to rotate Text in GDI+?

Community
  • 1
  • 1
LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • @LarsTech.Works like a Charm.Can you help me do this in the case of an image.I have added the Code Please see. – techno Nov 02 '11 at 01:51
3

before g.DrawString(mytext, font, brush, 0, 0); use g.RotateTransform(45);

Mazen313
  • 520
  • 4
  • 14