简体   繁体   中英

Adaptive letterSpacing in Text Jetpack Compose

How can I make letterSpacing adaptive to fill max width?

When I'm trying to set textAlign to Justify I get this: 图片 As you see, text is not filling max width.

When I'm adding non-zero letterSpacing argument to Text , I'm getting this result:

在此处输入图像描述 For longer text I'm getting weird result with letter stacking on each other. So, how can I make letterSpacing adaptive for each width?

Code:

Text(text = "07:30", 
     textAlign = TextAlign.Justify, 
     modifier = Modifier.fillMaxWidth(),
     //letterSpacing = 20.sp
)

@Pylyp Dukhov mentioned question that indirectly answers my question. So, we need to small down letterSpacing when text overflows it's parent and grow up when not overflows. Seems to be not the best solution, but better than nothing. Code:

var readyToDraw by remember { mutableStateOf(false) }
var letterSpacing by remember { mutableStateOf(50.sp) }
Text(
    text = "07:30",
    modifier = Modifier
        .drawWithContent {
            if (readyToDraw) drawContent()
        }
        .fillMaxWidth(),
    textAlign = TextAlign.Center,
    softWrap = false,
    letterSpacing = letterSpacing,
    onTextLayout = { result ->
        if (!readyToDraw) {
            if (!result.didOverflowWidth && letterSpacing < 80.sp) {
                letterSpacing *= 1.1f
                readyToDraw = true
            } else if (result.didOverflowWidth && letterSpacing > 5.sp) {
                letterSpacing *= 0.9f
            } else {
                readyToDraw = true
            }
        }
    }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM