2010-12-12 6 views
10

Je souhaite afficher une chaîne donnée dans un angle spécifique. J'ai essayé de le faire avec la classe System.Drawing.Font. Voici mon code:Comment faire pivoter Texte dans GDI +?

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

Quelqu'un peut-il me aider?

Répondre

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

REPRISES dE here.

10

Vous pouvez utiliser la méthode RotateTransform (see MSDN) pour spécifier la rotation pour tous les dessins sur Graphics (y compris le texte dessiné à l'aide DrawString). Le angle est en degrés:

graphics.RotateTransform(angle) 

Si vous voulez juste faire une opération pivotée unique, vous pouvez réinitialiser le fichier de transformation à l'état d'origine en appelant RotateTransform à nouveau avec un angle négatif (alternativement, vous pouvez utiliser ResetTransform, mais qui effacera toutes les transformations que vous avez appliqué qui ne peut être ce que vous voulez):

graphics.RotateTransform(-angle) 
+0

Je l'ai déjà essayé, mais alors tous mes graphiques dessinés sont tournés. Ce n'est pas très utile. – eagle999

+2

@ eagle999 utilisez ResetTransform() une fois que vous avez terminé de dessiner le texte pivoté –

7

Si vous voulez une méthode pour dessiner une chaîne mis en rotation à la position centrale de cordes, essayez la méthode suivante:

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

Meilleures salutations Hans Milling ...

+0

Vous êtes le héros !! Merci. –