2010-12-12 10 views
10

Quiero mostrar una cadena dada en un ángulo específico. Intenté hacer esto con la clase System.Drawing.Font. Aquí está mi código:Cómo rotar el texto en GDI +?

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

¿Puede alguien ayudarme?

Respuesta

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

tomado de here.

10

Puede utilizar el método RotateTransform (see MSDN) para especificar la rotación para todos sobre la base de Graphics (incluyendo texto elaborado utilizando DrawString). El angle es en grados:

graphics.RotateTransform(angle) 

Si quieres hacer una sola operación de girado, a continuación, puede restablecer la transformación al estado original llamando RotateTransform de nuevo con ángulo negativo (como alternativa, puede utilizar ResetTransform, pero que va a borrar todos los transformaciones que ha aplicado que pueden no ser lo que quiere):

graphics.RotateTransform(-angle) 
+0

ya he intentado esto, pero entonces todos mis gráficos dibujados se rotan. Eso no ayuda mucho. – eagle999

+2

@ eagle999 use ResetTransform() cuando haya terminado de dibujar el texto girado –

7

Si quieres un método para dibujar una cadena hace girar a la posición central cuerdas, a continuación, intente el método siguiente:

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

Saludos Hans fresado ...

+0

¡¡¡Usted es el héroe !! Gracias. –