方法: 四角形内にテキストを折り返して描画する

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

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

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

Screenshot that shows the output when using DrawString method.

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

  1. DrawString オーバーロード メソッドを使用して、目的のテキスト、Rectangle または RectangleFFont、および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 を使用して四角形内にテキストを折り返して描画するには

  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
    

コードのコンパイル

前の例では、以下が必要です。

関連項目