如何:在矩形中绘制换行文本
可以使用 Graphics 类的 DrawString 重载方法在矩形中绘制换行文本,该类采用 Rectangle 或 RectangleF 参数。 还可以使用 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 的一个参数。
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈