How to rotate Text in GDI+?
I want to display an given string in a specific angle. I tried to to 开发者_如何学Godo this with the System.Drawing.Font
class. Here is my code:
Font boldFont = new Font(FontFamily.GenericSansSerif, 12, FontStyle.Bold, GraphicsUnit.Pixel, 1, true);
graphics.DrawString("test", boldFont, textBrush, 0, 0);
Can anyone help me?
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();
Taken from here.
You can use the RotateTransform
method (see MSDN) to specify rotation for all drawing on Graphics
(including text drawn using DrawString
). The angle
is in degrees:
graphics.RotateTransform(angle)
If you want to do just a single rotated operation, then you can reset the transform to the original state by calling RotateTransform
again with negative angle (alternatively, you can use ResetTransform
, but that will clear all transformations that you applied which may not be what you want):
graphics.RotateTransform(-angle)
If you want a method to draw a rotated string at the strings center position, then try the following method:
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();
}
Best regards Hans Milling...
精彩评论