Tistory View

반응형

여러줄의 text를 출력하기 위해서는 고려해야 할 사항이 좀 많다. 줄이 출력하고자 하는 전체폭을 넘지 않는다면, 그냥 줄간격에 맞추어 출력을 하면되지만, 한 줄이 전체폭을 넘어간다면 단어에서 끊어주던지, 폭에 따른 글자에서 끊어 줘야 한다. 또한 한 단어가 한줄보다 클 경우는 단어내의 특정위치에서 또 끊어서 출력을 해야 한다. 이 고려할 사항도 사항이지만, 이 걸 일일이 계산해서 프로그래밍하는 것은 쉬운일은 아니다. 안드로이드에서는 이 과정을 한번에 해결해 주는 녀석이 있다. 땡큐 구글~

 

StaticLayout

다음은 StaticLayout을 이용하여 출력하는 코드이다.

StaticLayout mTextLayout = new StaticLayout( text, paint,
                width,
                Layout.Alignment.ALIGN_NORMAL,
                1.0f, 0.0f, false);

        canvas.save();
        canvas.translate( this.getPaddingLeft(), this.getPaddingRight() );
        mTextLayout.draw(canvas);
        canvas.restore();

 

StaticLayout의 생서자는 다음과 같다.

StaticLayout(CharSequence source, TextPaint paint, int width, Alignment align, float spacingmult, float spacingadd, boolean includepad)

 

width          : 가로 출력의 제한폭을 지정한다.

spacingmult : 1일 경우 Paint의 기본 lineHeight를 사용하며, 2를 넘기면 2줄의 세로 간격으로 출력 해준다.

spacingadd  : 줄간격의 추가 픽셀값을 지정한다.

 

실제 줄간격은 다음과 같이 계산된다.

줄간격 = paint의 줄간격 * spacingmult + spacingadd

 

이 외에도 다른 생성자가 있으니 살펴 보기를 바란다.

 

하지만 이 생성자방식은 (API 23 : MarshMallow)부터 Deprecated로 다른 방식을 써야 한다.

StaticLayout.Builder builder = StaticLayout.Builder.obtain(text, 0, text.length(), paint, width );
            StaticLayout textLayout = builder.build();

            canvas.save();
            canvas.translate( tx, ty );
            textLayout.draw(canvas);
            canvas.restore();

 

안드로이드의 버전에 따라서 구분하는 코드를 넣어 위의 두 코드를 섞어서 작성을 해야 한다.

Builder는 재사용을 하면 안되기 때문에 레이아웃이 변경되거나 폭이 바뀌거나 하면 다시 만들어서(obtain) 사용해야 한다.

 

버전에 따라 구분하여 출력하는 코드

private static void DrawMultilineText( Canvas canvas, String text, TextPaint paint, int width, float tx, float ty )
{
    StaticLayout textLayout = null;

    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M )
    {
        textLayout = new StaticLayout( text, paint, width, Layout.Alignment.ALIGN_NORMAL,
                1.0f, 0.0f, true );
    }
    else {
        StaticLayout.Builder builder = StaticLayout.Builder.obtain(text, 0, text.length(), paint, width );
        textLayout = builder.build();
    }

    canvas.save();
    canvas.translate( tx, ty );
    textLayout.draw(canvas);
    canvas.restore();
}

 

 

 

반응형
Replies
NOTICE
RECENT ARTICLES
RECENT REPLIES
Total
Today
Yesterday
LINK
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Article Box