in my app i have an id card composable which displays id card but on different screens the proportions are messed up because of variation in dpi so i wanted to have a text whose bounds are fixed and it should auto decide the text size to fit i looked up on google got some code which looks fine but somehow doesnt work
@Composable
fun AutoSizeText(
text: String,
modifier: Modifier = Modifier,
style: TextStyle = MaterialTheme.typography.bodyLarge,
color: Color,
) {
var reSized by remember{
mutableStateOf(style)
}
var shouldDraw by remember{
mutableStateOf(false)
}
if(!shouldDraw) reSized = reSized.copy(fontSize = 50.sp)
Text(
text = text,
color = color,
modifier = modifier.border(color = Color.Green,width = 1.dp).drawWithContent {
if(shouldDraw) drawContent()
},
softWrap = false,
maxLines = 1,
style = reSized,
onTextLayout = {
if(it.didOverflowHeight or it.didOverflowWidth){
reSized = reSized.copy(fontSize = reSized.fontSize * 0.999f)
}else{
shouldDraw = true
}
}
)
}
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
AutoSizeText(modifier = Modifier.height(36.dp),text = "${pass.id}", color = MaterialTheme.colorScheme.primaryContainer)
AutoSizeText(modifier = Modifier.height(36.dp),text = pass.purpose, color = MaterialTheme.colorScheme.primaryContainer)
Image(modifier = Modifier.size(36.dp), painter = painterResource(id = R.drawable.ic_logo), contentDescription = "logo", colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.primaryContainer))
}
as shown in the photo the green border is the size of the text which has fixed height of 36.dp and its width is automatic. the AutoTextSize is in a row.
the problem is the text is shrinking way to much as you can see it can clearly take more width and fit inside but it doesnt.
the first empty box never shows any text even though it has a 1 digit text.