Auto-Spaced Text in Jetpack Compose
Requirement
Modify the letter spacing of a Text
with a string and fixed width so that the Text
fills the complete width.
Note that the font size remains the same. Only the letter spacing will be responsive.
Text — onTextLayout
Text
composable has an attribute onTextLayout
that provides TextLayoutResult
data. This can be used to determine if the Text
is overflowing or not using hasVisualOverflow
value.
Modifier — drawWithContent
The drawWithContent
modifier can be used to skip UI rendering till the letter spacing calculation is completed.
drawContent()
inside the lambda is used to render the UI.
Logic
The logic is very simple.
We start with an minimumLetterSpacing
and we incrementally increase the letter spacing by a value of letterSpacingStep
till the text overflows.
Once the text overflows, we decrease the letter spacing by one letterSpacingStep
so that the text is within the given width and also update a flag to denote that the letter spacing calculation is completed.
Auto Spaced Text
TextUnit Extension functions
TextUnit
do not have plus and minus operators. So, we have created a Kotlin extension method for both of them.
Please comment with your valuable feedback. It would help me to improvise.
Kindly 👏👏👏 if this was useful.
Please follow if you would like to see more content related to Android Jetpack Compose.
LinkedIn: https://www.linkedin.com/in/abhimanyu-n/