androidandroid-jetpack-composeandroid-jetpackandroid-jetpack-compose-text

Incorrect rendering of text due to letterSpacing in Compose


I have a problem with letterSpacing in Compose. When I set TextAlign.End, TextOverflow.Ellipsis and style with letterSpacing text gets cut off. How can I fix this?

code:

val textStyleWithoutLetterSpacing = TextStyle()
val textStyleWithLetterSpacing = TextStyle(letterSpacing = 1.sp)

@Composable
fun Sample() {
    Column {
        Text(
            text = "1234567890 1234567890 1234567890",
            textAlign = TextAlign.End,
            overflow = TextOverflow.Ellipsis,
            maxLines = 1,
            style = textStyleWithoutLetterSpacing
        )
        Text(
            text = "1234567890 1234567890 1234567890",
            textAlign = TextAlign.End,
            overflow = TextOverflow.Ellipsis,
            maxLines = 1,
            style = textStyleWithLetterSpacing
        )
    }
}

result: 1


Solution

  • I faced a similar issue which I believe has to do with combining textAlign = TextAlign.End with overflow = TextOverflow.Ellipsis. I have just had a play with you sample and came up with this (which is similar to how I solved my problem):

    val textStyleWithoutLetterSpacing = TextStyle()
    val textStyleWithLetterSpacing = TextStyle(letterSpacing = 1.sp)
    
    @Composable
    fun Sample() {
        Column {
            Text(
                text = "1234567890 1234567890 1234567890",
                textAlign = TextAlign.End,
                overflow = TextOverflow.Ellipsis,
                maxLines = 1,
                style = textStyleWithoutLetterSpacing
            )
    
            Box(contentAlignment = Alignment.CenterEnd) {
                Text(
                    text = "1234567890 1234567890 1234567890",
                    overflow = TextOverflow.Ellipsis,
                    maxLines = 1,
                    style = textStyleWithLetterSpacing
                )
            }
        }
    }
    

    In essence, I delegated the alignment of the text to the Box component and that seems to bypass the bug in the compose library (v1.2.1 at the time of writing this answer).