【问题标题】:Drawing a Rotated Text to an Image in C#在 C# 中将旋转的文本绘制到图像中
【发布时间】:2011-11-01 14:15:27
【问题描述】:

我正在使用 Graphics 类的 drawstring 方法在 Image 上绘制一个字符串。

  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;

文本是以旋转的角度绘制的,但它没有按我的意愿绘制在中心。请帮帮我。

【问题讨论】:

  • 向我们展示您尝试过的旋转变换代码。
  • 您能否向我们展示整个方法(例如,这是 OnPaint 事件)吗?另外,你能告诉我们你得到了什么结果吗?

标签: c# .net graphics drawing rotation


【解决方案1】:

如果您想使文本居中,仅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+?

【讨论】:

  • @LarsTech.Works 就像一个魅力。你能帮我在图像的情况下这样做吗。我已经添加了代码请看。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2017-06-13
    • 2016-04-07
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 2011-05-30
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多