[Compose] buildAnnotatedString

호야·2022년 10월 8일
0
post-thumbnail

bulidAnnotatedString 이란

AnnotatedString 객체를 만드는 inline function 이다.

AnnotatedString 이란

동일한 Text 컴포저블 내에서 여러 스타일을 설정할 수 있도록 하는 객체이다.

AnotatedString 은 다음 항목이 포함되어 있다.

  • Text
  • SpanStyle: 텍스트 크기, 간격 등
  • ParagraphStyle: 텍스트 정렬, 텍스트 방향, 줄 간격, 텍스트 들여쓰기 스타일 지정
  • Annotations

SpanStyle 과 ParagraphStyle 의 차이점

ParagraphStyle 은 전체 단락에 적용할 수 있고 SpanStyle 은 문자 수준에서 적용할 수 있다.

예제 코드

// use SpanStyle
Text(
    buildAnnotatedString {
        withStyle(
            style = SpanStyle(
                color = Color.Blue
            )
        ) {
            append("H")
        }
        append("ello ")
        withStyle(
            style = SpanStyle(
                fontWeight = FontWeight.Bold,
                color = Color.Red
            )
        ) {
            append("W")
        }
        append("orld")
    }
)
// use ParagraphStyle
Text(
    buildAnnotatedString {
        withStyle(style = ParagraphStyle(lineHeight = 30.sp)) {
            withStyle(
                style = SpanStyle(
                    color = Color.Blue
                )
            ) {
                append("Hello\n")
            }
            withStyle(
                style = SpanStyle(
                    fontWeight = FontWeight.Bold,
                    color = Color.Red
                )
            ) {
                append("World\n")
            }
            append("Compose")
        }
    }
)

참고 자료

https://developer.android.com/jetpack/compose/text?hl=ko
https://kotlinworld.com/224

0개의 댓글