如何在GDI +中旋转文本?

时间:2010-12-12 11:24:56

标签: c# gdi+

我想以特定角度显示给定的字符串。我试图用System.Drawing.Font类来做这件事。这是我的代码:

Font boldFont = new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold, GraphicsUnit.Pixel, 1, true);
graphics.DrawString("test", boldFont, textBrush, 0, 0);

任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:15)

String theString = "45 Degree Rotated Text";
SizeF sz = e.Graphics.VisibleClipBounds.Size;
//Offset the coordinate system so that point (0, 0) is at the
center of the desired area.
e.Graphics.TranslateTransform(sz.Width / 2, sz.Height / 2);
//Rotate the Graphics object.
e.Graphics.RotateTransform(45);
sz = e.Graphics.MeasureString(theString, this.Font);
//Offset the Drawstring method so that the center of the string matches the center.
e.Graphics.DrawString(theString, this.Font, Brushes.Black, -(sz.Width/2), -(sz.Height/2));
//Reset the graphics object Transformations.
e.Graphics.ResetTransform();

取自here

答案 1 :(得分:10)

您可以使用RotateTransform方法(see MSDN)为Graphics上的所有绘图指定轮播(包括使用DrawString绘制的文字)。 angle以度为单位:

graphics.RotateTransform(angle)

如果您只想进行一次旋转操作,则可以通过以负角度再次调用RotateTransform来将变换重置为原始状态(或者,您可以使用ResetTransform,但这样做会清除您应用的所有转换(可能不是您想要的):

graphics.RotateTransform(-angle)

答案 2 :(得分:9)

如果您想要一种方法在字符串中心位置绘制旋转的字符串,请尝试以下方法:

public void drawRotatedText(Bitmap bmp, int x, int y, float angle, string text, Font font, Brush brush)
{
  Graphics g = Graphics.FromImage(bmp);
  g.TranslateTransform(x, y); // Set rotation point
  g.RotateTransform(angle); // Rotate text
  g.TranslateTransform(-x, -y); // Reset translate transform
  SizeF size = g.MeasureString(text, font); // Get size of rotated text (bounding box)
  g.DrawString(text, font, brush, new PointF(x - size.Width / 2.0f, y - size.Height / 2.0f)); // Draw string centered in x, y
  g.ResetTransform(); // Only needed if you reuse the Graphics object for multiple calls to DrawString
  g.Dispose();
}

祝你好运   汉斯米林......