Text

- 화면에 문자열 출력 시 사용


오버로딩

- 6가지 오버로딩 제공

- 다만 일부 매개변수를 미지원하는 케이스들을 제외하면 실질적으로 2가지 오버로딩

 

1. 기본 String 형태

@Composable
fun Text(
    text: String,                                           // 출력할 문자열
    modifier: Modifier = Modifier,                          // Modifier
    color: Color = Color.Unspecified,                       // 글자의 색상
    autoSize: TextAutoSize? = null,                         // 텍스트가 주어진 공간에 맞춰 크기 조절
    fontSize: TextUnit = TextUnit.Unspecified,              // 글자의 크기
    fontStyle: FontStyle? = null,                           // 글자의 기울임 여부(Italic)
    fontWeight: FontWeight? = null,                         // 글자의 굵기(Bold)
    fontFamily: FontFamily? = null,                         // 글꼴 Family
    letterSpacing: TextUnit = TextUnit.Unspecified,         // 글자 사이의 간격(자간)
    textDecoration: TextDecoration? = null,                 // 밑줄, 취소선
    textAlign: TextAlign? = null,                           // 글자의 수평 정렬 방식
    lineHeight: TextUnit = TextUnit.Unspecified,            // 줄 간격(행간)
    overflow: TextOverflow = TextOverflow.Clip,             // 텍스트가 주어진 공간을 벗어날때 처리 방식
    softWrap: Boolean = true,                               // 자동 줄바꿈 여부
    maxLines: Int = Int.MAX_VALUE,                          // 최대 줄 수
    minLines: Int = 1,                                      // 최소 줄 수
    onTextLayout: ((TextLayoutResult) -> Unit)? = null,     // 텍스트 Layout 계산 완료시 호출되는 콜백
    style: TextStyle = LocalTextStyle.current,              // 텍스트의 전반적인 서식
)

 

1) color

- 아래 색상들을 기본제공

- Color.Unspecified인 경우 style에 정의된 색상이나 기본 색상을 따름

Black = Color(0xFF000000)
DarkGray = Color(0xFF444444)
Gray = Color(0xFF888888)
LightGray = Color(0xFFCCCCCC)
White = Color(0xFFFFFFFF)
Red = Color(0xFFFF0000)
Green = Color(0xFF00FF00)
Blue = Color(0xFF0000FF)
Yellow = Color(0xFFFFFF00)
Cyan = Color(0xFF00FFFF)
Magenta = Color(0xFFFF00FF)
Transparent = Color(0x00000000)
Unspecified = Color(0f, 0f, 0f, 0f, ColorSpaces.Unspecified)

 

2) autoSize

- text가 주어진 공간에 맞춰 크기 조절하는 방식을 설정

- stepSize가 1.sp라면 정밀도가 1로 지정되어 10.sp로는 들어가는데 11.sp로는 못들어간다면 10.sp로 설정

  - 반면 0.1.sp라면 정밀도가 0.1로 지정되여 11.sp로는 못들어가는데 10.9.sp로는 들어가진다면 10.9.sp로 설정

Text(
    text = "Hello Kotlin",
    modifier = Modifier,
    autoSize = TextAutoSize.StepBased(
        minFontSize = 12.sp,             // 텍스트가 줄어들 수 있는 최소 크기(기본값 12.sp)
        maxFontSize = 112.sp,            // 텍스트가 늘어날 수 있는 최대 크기(기본값 112.sp)
        stepSize = 0.25.sp               // 텍스트 크기를 조절할때 간격(기본값 0.25.sp)
    )
)

 

3) fontWeight

- 글자의 굵기 지정

- 숫자가 높을수록 두껍고 숫자로 지정도 가능하고 예약어로 아래 문구들이 제공됨

fontWeight = FontWeight(100)
// 혹은
fontWeight = FontWeight.W100

Thin = W100
ExtraLight = W200
Light = W300
Normal = W400
Medium = W500
SemiBold = W600
Bold = W700
ExtraBold = W800
Black = W900

 

4) textDecoration

textDecoration = TextDecoration.Underline   // 밑줄
textDecoration = TextDecoration.LineThrough // 취소선

textDecoration = TextDecoration.combine(    // 밑줄과 취소선 둘 다 적용
    listOf(TextDecoration.Underline, TextDecoration.LineThrough)
)

textDecoration = TextDecoration.None        // 효과 제거(기본값이기도 하고, 전역 Style 적용 안하고 싶을 때)

 

5) textAlign

textAlign = TextAlign.Center   // 가운데 정렬

textAlign = TextAlign.End      // 오른쪽 끝 정렬, RTL시 Start/End는 자동적용되므로 Start/End 권장
textAlign = TextAlign.Right

textAlign = TextAlign.Start    // 왼쪽 끝 정렬, 기본값
textAlign = TextAlign.Left

textAlign = TextAlign.Justify  // 양쪽 맞춤 정렬

 

6) overflow

- 문구가 공간을 넘어가는 경우 어떻게 처리할지 설정

- maxLines 설정 후 해당 줄 수를 넘어가면 overflow 정책에 따라 처리

- softWrap false 설정 후 사용 가능한 너비를 넘어가면 overflow 정책에 따라 처리

overflow = TextOverflow.Ellipsis          // 뒤를 자르고 ...으로 표시
overflow = TextOverflow.MiddleEllipsis    // 중간부분을 ...으로 표시(ex. C:\Users\...\Desktop)
overflow = TextOverflow.StartEllipsis     // 시작부분을 ...으로 표시
overflow = TextOverflow.Clip              // 말줄임표 없이 그냥 자르고 미표출
overflow = TextOverflow.Visible           // 영역을 벗어나 튀어나가더라도 그냥 표시

 

7) softWrap

- true인 경우 문구가 사용 가능한 너비를 넘어가면 줄바꿈을 허용

- false인 경우 문구가 사용 가능한 너비를 넘어가면 줄바꿈 없이 한줄로 길게 이어나감

 

8) onTextLayout

- 계산된 텍스트의 width, height, lineCount등의 상세정보를 TextLayoutResult를 통해 받아볼 수 있음

Text(
    text = "아주 긴 텍스트...",
    overflow = TextOverflow.Ellipsis,
    onTextLayout = { textLayoutResult ->
        
        if (textLayoutResult.didOverflowHeight || textLayoutResult.didOverflowWidth) {
            // 하단이나 옆으로 넘쳤는지 확인
            isOverflowed = true
        }
        
        val boundingBox = textLayoutResult.getBoundingBox(6) // 특정 글자가 그려진 좌표 획득
        println("6번째 글자의 위치: ${boundingBox.left}, ${boundingBox.top}")
        
        lineCount = textLayoutResult.lineCount
        println("현재 텍스트는 총 ${textLayoutResult.lineCount}줄입니다.")
        
        // 이외에도 getLineForOffset(offset)으로 특정 글자가 몇번째 줄에 있는지 획득
        // getOffsetForPosition(offset)으로 특정 좌표(x, y)에 있는 글자의 인덱스 반환
        // 등등...
    }
)

 

2. AnnotatedString 형태

@Composable
fun Text(
    text: AnnotatedString,                                         // 주요 차이점
    modifier: Modifier = Modifier,
    color: Color = Color.Unspecified,
    autoSize: TextAutoSize? = null,
    fontSize: TextUnit = TextUnit.Unspecified,
    fontStyle: FontStyle? = null,
    fontWeight: FontWeight? = null,
    fontFamily: FontFamily? = null,
    letterSpacing: TextUnit = TextUnit.Unspecified,
    textDecoration: TextDecoration? = null,
    textAlign: TextAlign? = null,
    lineHeight: TextUnit = TextUnit.Unspecified,
    overflow: TextOverflow = TextOverflow.Clip,
    softWrap: Boolean = true,
    maxLines: Int = Int.MAX_VALUE,
    minLines: Int = 1,
    inlineContent: Map<String, InlineTextContent> = mapOf(),      // 주요 차이점
    onTextLayout: (TextLayoutResult) -> Unit = {},
    style: TextStyle = LocalTextStyle.current,
)

 

1) AnnotatedString

- 스타일이 입혀진 문자열

- 일반 String은 텍스트 전체에 하나의 스타일만 적용가능(문구 전체가 빨간색 등)

- AnnotatedString은 문자열의 턱정 구간마다 서로 다른 스타일 지정 가능

val annotatedString = buildAnnotatedString {
    append("안녕하세요 ")
    withStyle(style = SpanStyle(color = Color.Red, fontWeight = FontWeight.Bold)) {
        append("코틀린")
    }
    append("입니다.")
}
Text(text = annotatedString)

// 코틀린 문구만 빨간색에 두껍게
// withStyle()함수의 style 파라미터에 SpanStyle 객체나 ParagraphStyle객체로 설정
// SpanStyle : 문구에 적용하는 스타일
// ParagraphStyle : 줄간격이나 정렬같은 문단단위 스타일

 

2) inlineContent

- 텍스트 중간에 아이콘, 이미지, 컴포저블을 글자처럼 끼워넣음

  - 텍스트의 시작이나 끝에 아이콘을 넣을땐 그냥 Row 쓰는게 더 쉽고, 중간에 넣을때만 사용하는것으로 보임

val myId = "inlineIcon"
val text = buildAnnotatedString {
    append("좋아요를 눌러주세요 ")
    appendInlineContent(myId, "[icon]") // 아이콘이 들어갈 자리 예약
}

val inlineContent = mapOf(              // inlineContent 생성
    myId to InlineTextContent(
        Placeholder(20.sp, 20.sp, PlaceholderVerticalAlign.Center)
    ) {
        Icon(Icons.Default.Favorite, contentDescription = null, tint = Color.Red)
    }
)

Text(
    text = text,
    inlineContent = inlineContent
)