2010-12-12 14 views
10

Desidero visualizzare una determinata stringa in un angolo specifico. Ho provato a farlo con la classe System.Drawing.Font. Ecco il mio codice:Come ruotare il testo in GDI +?

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

Qualcuno mi può aiutare?

risposta

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

Tratto da here.

10

È possibile utilizzare il metodo RotateTransform (see MSDN) per specificare la rotazione per tutti (il testo compreso disegnato con DrawString) attingendo Graphics. Il angle è in gradi:

graphics.RotateTransform(angle) 

Se si vuole fare solo una singola operazione ruotato, allora si può ripristinare la trasformazione allo stato originale chiamando RotateTransform di nuovo con angolo negativo (in alternativa, è possibile utilizzare ResetTransform, ma che sarà chiaro tutti trasformazioni che avete applicato che non può essere quello che vuoi):

graphics.RotateTransform(-angle) 
+0

Ho già provato questo, ma poi tutte le mie grafiche disegnate vengono ruotate. Questo non aiuta molto. – eagle999

+2

@ eagle999 usa ResetTransform() dopo aver finito di disegnare il testo ruotato –

7

Se si desidera un metodo per disegnare una stringa ruotato in posizione centrale stringhe, quindi provare il seguente metodo:

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

migliori saluti Hans fresatura ...

+0

Sei l'eroe !! Grazie. –

Problemi correlati