如何:在矩形中绘制换行文本

可以使用Graphics类的重载方法,该方法接受RectangleRectangleF参数,从而在矩形DrawString中绘制换行文本。 你还将使用BrushFont

还可以使用DrawText采用 a RectangleTextFormatFlags参数的TextRenderer重载方法在矩形中绘制包装文本。 你还将使用一个 Color 和一个 Font

下图显示了使用 DrawString 该方法时在矩形中绘制的文本输出:

显示使用 DrawString 方法时的输出的屏幕截图。

使用 GDI+ 在矩形中绘制包装文本

  1. 使用DrawString重载方法,传递所需的文本RectangleRectangleFFontBrush

    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 在矩形中绘制包装文本

  1. 使用TextFormatFlags枚举值来指定文本应通过DrawText重载方法进行包装,并传递您想要的文本RectangleFontColor

    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
    

编译代码

前面的示例需要:

另请参阅