Share via


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

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

您也可以使用 DrawText 採用 RectangleTextFormatFlags 參數之 TextRenderer 的多載方法,在矩形中繪製包裝文字。 您也將使用 ColorFont

下圖顯示當您使用 DrawString 方法時,在矩形中繪製的文字輸出:

Screenshot that shows the output when using DrawString method.

使用 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 多載方法包裝、傳遞您想要 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
    

編譯程式碼

上述範例需要:

另請參閱