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

tec*_*hno 9 .net c# graphics drawing rotation

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

  g.DrawString(mytext, font, brush, 0, 0);
Run Code Online (Sandbox Code Playgroud)

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

    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;
Run Code Online (Sandbox Code Playgroud)

文本是以旋转的角度绘制的,但它不是在我想要的中心绘制.Plz帮助我.

Lar*_*ech 26

仅仅RotateTransform或者TranslateTranform如果你想让文本居中是不够的.您还需要通过测量来偏移文本的起始点:

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));
}
Run Code Online (Sandbox Code Playgroud)

如何在GDI +中旋转文本?