如何:在矩形中繪製被包圍的文字
您可以使用採用 Rectangle 或 RectangleF 參數之 Graphics 類別的 DrawString 多載方法,在矩形中繪製圍繞文字。 您也將使用 Brush 與 Font。
您也可以使用採用 Rectangle 和 TextFormatFlags 參數之 TextRenderer 的 DrawText 多載方法,在矩形中繪製圍繞文字。 您也將使用 Color 與 Font。
下圖顯示當您使用 DrawString 方法時,在矩形中繪製的文字輸出:
若要使用 GDI+ 在矩形中繪製圍繞文字
使用 DrawString 多載方法,傳遞您想要的文字,Rectangle 或 RectangleF、Font 和 Brush。
string text1 = "Draw text in a rectangle by passing a RectF to the DrawString method."; using (Font font1 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point)) { RectangleF rectF1 = new RectangleF(30, 10, 100, 122); e.Graphics.DrawString(text1, font1, Brushes.Blue, rectF1); e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(rectF1)); }
Dim text1 As String = "Draw text in a rectangle by passing a RectF to the DrawString method." Dim font1 As New Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point) Try Dim rectF1 As New RectangleF(30, 10, 100, 122) e.Graphics.DrawString(text1, font1, Brushes.Blue, rectF1) e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(rectF1)) Finally font1.Dispose() End Try
若要使用 GDI 在矩形中繪製圍繞文字
使用 TextFormatFlags 列舉值來指定文字應該以 DrawText 多載方法圍繞、傳遞您想要的文字,Rectangle、Font 和 Color。
string text2 = "Draw text in a rectangle by passing a RectF to the DrawString method."; using (Font font2 = new Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point)) { Rectangle rect2 = new Rectangle(30, 10, 100, 122); // Specify the text is wrapped. TextFormatFlags flags = TextFormatFlags.WordBreak; TextRenderer.DrawText(e.Graphics, text2, font2, rect2, Color.Blue, flags); e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(rect2)); }
Dim text2 As String = _ "Draw text in a rectangle by passing a RectF to the DrawString method." Dim font2 As New Font("Arial", 12, FontStyle.Bold, GraphicsUnit.Point) Try Dim rect2 As New Rectangle(30, 10, 100, 122) ' Specify the text is wrapped. Dim flags As TextFormatFlags = TextFormatFlags.WordBreak TextRenderer.DrawText(e.Graphics, text2, font2, rect2, Color.Blue, flags) e.Graphics.DrawRectangle(Pens.Black, Rectangle.Round(rect2)) Finally font2.Dispose() End Try
編譯程式碼
上述範例需要:
- PaintEventArgs
e
,這是 PaintEventHandler 的參數。