如何:在矩形中繪製被包圍的文字
您可以使用採用 Rectangle 或 RectangleF 參數之 類別的多 Graphics 載方法,在矩形 DrawString 中繪製包裝文字。 您也將使用 Brush 和 Font 。
您也可以使用 DrawText 採用 Rectangle 和 TextFormatFlags 參數之 TextRenderer 的多載方法,在矩形中繪製包裝文字。 您也將使用 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 多載方法包裝、傳遞您想要 RectangleFont 的文字和 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 。
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應