如何:对齐绘制的文本
更新:2007 年 11 月
执行自定义绘制时,您可能常常希望在窗体或控件中使绘制的文本居中。通过创建正确的格式设置对象和设置适当的格式标志,可以轻松地对齐用 DrawString 或 DrawText 方法绘制的文本。
用 GDI+ (DrawString) 绘制居中文本
将 StringFormat 与适当的 DrawString 方法一起使用以指定居中文本。
Dim text1 As String = "Use StringFormat and Rectangle objects to" & _ " center text in a rectangle." Dim font1 As New Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point) Try Dim rect1 As 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. Dim stringFormat As 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) Finally font1.Dispose() End Try
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); }
用 GDI (DrawText) 绘制居中文本
将 TextFormatFlags 枚举与适当的 DrawText 方法一起使用以进行换行以及使文本垂直和水平居中。
Dim text2 As String = "Use TextFormatFlags and Rectangle objects to" & _ " center text in a rectangle." Dim font2 As New Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point) Try Dim rect2 As New Rectangle(150, 10, 130, 140) ' Create a TextFormatFlags with word wrapping, horizontal center and ' vertical center specified. Dim flags As TextFormatFlags = TextFormatFlags.HorizontalCenter Or _ TextFormatFlags.VerticalCenter Or TextFormatFlags.WordBreak ' Draw the text and the surrounding rectangle. TextRenderer.DrawText(e.Graphics, text2, font2, rect2, Color.Blue, flags) e.Graphics.DrawRectangle(Pens.Black, rect2) Finally font2.Dispose() End Try
string text2 = "Use TextFormatFlags and Rectangle objects to" + " center text in a rectangle."; using (Font font2 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point)) { Rectangle rect2 = new Rectangle(150, 10, 130, 140); // Create a TextFormatFlags with word wrapping, horizontal center and // vertical center specified. TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak; // Draw the text and the surrounding rectangle. TextRenderer.DrawText(e.Graphics, text2, font2, rect2, Color.Blue, flags); e.Graphics.DrawRectangle(Pens.Black, rect2); }
编译代码
前面的代码示例旨在用于 Windows 窗体,这些示例需要作为 PaintEventHandler 参数的 PaintEventArgse。