When you perform custom drawing, you may often want to center drawn text on a form or control. You can easily align text drawn with the DrawString or DrawText methods by creating the correct formatting object and setting the appropriate format flags.
Use a StringFormat with the appropriate DrawString method to specify centered text.
string text1 = "Use StringFormat and Rectangle objects to" + " center text in a rectangle."; using (Font font1 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point)) { Rectangle rect1 = new Rectangle(10, 10, 130, 140); // Create a StringFormat object with the each line of text, and the block // of text centered on the page. StringFormat stringFormat = new StringFormat(); stringFormat.Alignment = StringAlignment.Center; stringFormat.LineAlignment = StringAlignment.Center; // Draw the text and the surrounding rectangle. e.Graphics.DrawString(text1, font1, Brushes.Blue, rect1, stringFormat); e.Graphics.DrawRectangle(Pens.Black, rect1); }
0 comments:
Post a Comment