在C#中将旋转的文本绘制到图像

时间:2011-11-01 14:15:28

标签: c# .net graphics drawing rotation

我正在使用Graphics类的drawtring方法在Image上绘制一个String。

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

我正在尝试使用图形对象的旋转变换功能按角度旋转文本,以便可以以任何角度绘制文本。如何使用旋转变换来执行此操作。 我使用的旋转变换代码是

    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;

文字是以旋转的角度绘制的,但它并没有像我想的那样在中心绘制.Plz帮帮我。

2 个答案:

答案 0 :(得分:26)

如果您想要将文本居中,仅仅RotateTransformTranslateTranform是不够的。您还需要通过测量来偏移文本的起点:

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));
}

来自How to rotate Text in GDI+?

答案 1 :(得分:2)

g.DrawString(mytext, font, brush, 0, 0);使用g.RotateTransform(45);

之前