如何:在矩形中繪製被包圍的文字

您可以使用採用 RectangleRectangleF 參數之 Graphics 類別的 DrawString 多載方法,在矩形中繪製圍繞文字。 您也將使用 BrushFont

您也可以使用採用 RectangleTextFormatFlags 參數之 TextRendererDrawText 多載方法,在矩形中繪製圍繞文字。 您也將使用 ColorFont

下圖顯示當您使用 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
    

編譯程式碼

上述範例需要:

另請參閱