방법: 사각형 안에 줄 바꿈된 텍스트 그리기

Rectangle 또는 RectangleF 매개 변수를 사용하는 Graphics 클래스의 DrawString 오버로드된 메서드를 사용하여 사각형에 래핑된 텍스트를 그릴 수 있습니다. BrushFont도 사용합니다.

RectangleTextFormatFlags 매개 변수를 사용하는 TextRendererDrawText 오버로드된 메서드를 사용하여 사각형에 래핑된 텍스트를 그릴 수도 있습니다. ColorFont도 사용합니다.

다음 그림에서는 DrawString 메서드를 사용할 때 사각형에 그려진 텍스트의 출력을 보여 줍니다.

DrawString 메서드를 사용할 때 출력을 보여주는 스크린샷.

GDI+를 사용하여 사각형에 래핑된 텍스트를 그리려면 다음을 수행합니다.

  1. DrawString 오버로드된 메서드를 사용하여 원하는 텍스트인 Rectangle 또는 RectangleF, Font, 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 오버로드된 메서드로 래핑되어야 하며 원하는 텍스트인 Rectangle, Font, 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
    

코드 컴파일

이전 예제에는 다음이 필요합니다.

참고 항목