可以使用Graphics类的重载方法,该方法接受Rectangle或RectangleF参数,从而在矩形DrawString中绘制换行文本。 你还将使用Brush 和Font。
还可以使用DrawText采用 a 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重载方法进行包装,并传递您想要的文本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 的一个参数。