2010-12-12 15 views
10

Chcę wyświetlić dany ciąg pod określonym kątem. Próbowałem to zrobić z klasą System.Drawing.Font. Tu jest mój kodu:Jak obrócić tekst w GDI +?

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

Czy ktoś może mi pomóc?

Odpowiedz

16
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(); 

zaczerpnięte z here.

10

Można użyć metody RotateTransform (see MSDN), aby określić obrót dla wszystkich rysunek na Graphics (w tym tekstu opracowanego przy użyciu DrawString). angle jest w stopniach:

graphics.RotateTransform(angle) 

Jeśli chcesz zrobić tylko jedną obróconego operację, a następnie można zresetować transformacji do stanu pierwotnego poprzez wywołanie RotateTransform ponownie z ujemnym kątem (alternatywnie można użyć ResetTransform, ale że usunie wszystkie transformacje, które stosowane które mogą nie być, co chcesz):

graphics.RotateTransform(-angle) 
+0

ja już próbowałem, ale następnie wszystkie moje rysowane grafiki są obracane. To niewiele pomaga. – eagle999

+2

@ eagle999 użyć ResetTransform() po zakończeniu rysowania obróconego tekstu –

7

Jeśli chcesz sposób narysować obrócony łańcuch na środkowej pozycji struny, a następnie spróbować następującej metody:

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

poważaniem Hans frezowania ...

+0

Jesteś bohaterem !! Dzięki. –