ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Jetpack Compose] 크기가 자동 조정되는 Text
    카테고리 없음 2024. 3. 27. 20:38

    사용 이유

    개인 프로젝트를 하면서 글자 길이가 긴 것들만 일부 줄여서 사용하기 귀찮아서 구글링을 하며 만들어보았다.

     

    작동 방식

    onTextLayout이 글자의 레이아웃이 계산될 때 호출되는 콜백이다.

    여기서 it.didOverflowWidth를 사용해서 체크하여 위에 선언해 두었던 newFontSize에 0.95를 곱하여 줄인다.

    (didOverflowWidth는 가로 길이가 넘어갈 때 true를 반환하는 프로퍼티이다.)

    그렇게 가로 길이가 초과되지 않을 때까지 콜백이 반복되어 글자가 줄어들게 된다.

    @Composable
    fun Text(
        modifier: Modifier = Modifier,
        text: Any,
        fontSize: TextUnit,
        textAlign: TextAlign? = null,
        fontWeight: FontWeight = FontWeight.Light,
        color: Color = Color.Black
    ) {
        var newFontSize by remember { mutableStateOf(fontSize) }
        androidx.compose.material3.Text(
            text = text.toString(),
            textAlign = textAlign,
            color = color,
            fontFamily = Font.esamanru,
            fontWeight = fontWeight,
            fontSize = newFontSize,
            modifier = modifier,
            softWrap = false,
            overflow = TextOverflow.Visible,
            onTextLayout = {
                if (it.didOverflowWidth) {
                    newFontSize *= 0.95
                }
            }
        )
    }
Designed by Tistory.