Is there such thing as an auto size text view in c...
# compose
c
Is there such thing as an auto size text view in compose? I searched cs.android.com without being able to find anything related to compose. Like this?

https://www.youtube.com/watch?v=JYrpEAz_A1U

z
I don’t think it’s built in right now but theoretically shouldn’t be too hard to build.
s
@Zach Klippenstein (he/him) [MOD] probably using
NativePaint.breakText
?
z
I think you can do it without dropping down to any native stuff
3
s
@Zach Klippenstein (he/him) [MOD] Is this correct approach ??
Copy code
@Composable
@InternalTextApi
fun calculateTextSize(constraints: Constraints, text: AnnotatedString, textSize: TextUnit): TextUnit {
    val textDelegate = TextDelegate(
        text = text,
        style = MaterialTheme.typography.h6.copy(fontSize = textSize),
        maxLines = 1,
        density = LocalDensity.current,
        resourceLoader = object : Font.ResourceLoader {
            override fun load(font: Font): Any {
                return false
            }
        }
    )
    val layoutResult = textDelegate.layout(constraints, LayoutDirection.Ltr)

    return if (layoutResult.didOverflowHeight) {
        Log.d("TAG", "Delegate text size again $textSize")
        calculateTextSize(constraints, text, textSize - 2.sp)
    } else {
        Log.d("TAG", "Delegate text size done $textSize")
        //debug { "Delegate text size done $textSize" }
        textSize
    }
}
c
@Siyamed may have insight
z
I don’t think recursion is the best approach – you can start with a known text size, measure, then calculate how much to adjust the text size based on the difference between the measured size and the constraints
👍 2
👍🏼 1
s
@Zach Klippenstein (he/him) [MOD] Can you please help, how can I achieve this part? "calculate how much to adjust the text size based on the difference between the measured size and the constraints"?
z
Pick a size, measure with that, then scale the size proportional to the difference between that and constraints