次の方法で共有


方法: 四角形に折り返されたテキストを描画する

DrawStringまたはGraphicsパラメーターを受け取るRectangle クラスのRectangleFオーバーロードされたメソッドを使用して、四角形で折り返されたテキストを描画できます。 また、 BrushFontも使用します。

また、DrawTextTextRenderer パラメーターを受け取るRectangleTextFormatFlagsオーバーロードメソッドを使用して、折り返されたテキストを四角形に描画することもできます。 また、 ColorFontも使用します。

次の図は、 DrawString メソッドを使用するときに四角形に描画されるテキストの出力を示しています。

DrawString メソッドを使用するときの出力を示すスクリーンショット。

GDI+ を使用して折り返されたテキストを四角形に描画するには

  1. DrawStringオーバーロードされたメソッドを使用して、必要なテキスト、RectangleまたはRectangleFFontBrushを渡します。

    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
    

コードのコンパイル

前の例では、次のものが必要です。

こちらも参照ください