-
-
Save mustfaunlu/3396beb163bf8d9a534b0f63cd199d31 to your computer and use it in GitHub Desktop.
Auto Resize Text in Jetpack Compose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Composable | |
fun AutoTextSizeCard() { | |
var textLength by remember { mutableStateOf(50) } | |
val baseText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " | |
val longText = baseText.repeat(textLength / baseText.length + 1).substring(0, textLength) | |
Card( | |
modifier = Modifier | |
.fillMaxWidth() | |
.height(300.dp) | |
.padding(16.dp), | |
elevation = CardDefaults.elevatedCardElevation(4.dp) | |
) { | |
Column( | |
modifier = Modifier | |
.fillMaxSize() | |
.padding(16.dp) | |
) { | |
Box( | |
modifier = Modifier | |
.fillMaxWidth() | |
.weight(1f) | |
) { | |
AutoResizeText( | |
text = longText, | |
modifier = Modifier.fillMaxSize() | |
) | |
} | |
Spacer(modifier = Modifier.height(16.dp)) | |
Slider( | |
value = textLength.toFloat(), | |
onValueChange = { textLength = it.toInt() }, | |
valueRange = 50f..5000f | |
) | |
} | |
} | |
} | |
@Composable | |
fun AutoResizeText( | |
text: String, | |
modifier: Modifier = Modifier | |
) { | |
val textSize by remember { mutableStateOf(14.sp) } | |
BoxWithConstraints(modifier = modifier) { | |
val constraints = this.constraints | |
var resizedTextSize by remember { mutableStateOf(textSize) } | |
BasicText( | |
text = text, | |
style = TextStyle(fontSize = resizedTextSize, fontWeight = FontWeight.Normal), | |
onTextLayout = { textLayoutResult -> | |
if (textLayoutResult.didOverflowHeight || textLayoutResult.didOverflowWidth) { | |
resizedTextSize *= 0.9 | |
} | |
}, | |
modifier = Modifier.fillMaxSize() | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment