HOW TO:對齊繪製的文字
更新: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 Form 搭配使用而設計的,而且需要 PaintEventArgse(即 PaintEventHandler 的參數)。