Denis
01/30/2021, 12:18 PMTextDelegate
? There was a similar question before [1]. I want to render some text matching a particular width. I used code from [2], but can't make it work.
@Preview
@Composable
fun TextAutoSize() {
class TestFontResourceLoader(val context: Context) : Font.ResourceLoader {
override fun load(font: Font): android.graphics.Typeface {
return when (font) {
is ResourceFont -> ResourcesCompat.getFont(context, font.resId)!!
else -> throw IllegalArgumentException("Unknown font type: $font")
}
}
}
val textDelegate = TextDelegate(
text = AnnotatedString("Hello, World"),
style = TextStyle.Default,
maxLines = 1,
density = Density(density = 1f),
resourceLoader = TestFontResourceLoader(AmbientContext.current),
)
val layoutResult = textDelegate.layout(Constraints.fixedWidth(1000), LayoutDirection.Ltr)
Canvas(Modifier.fillMaxWidth().height(50.dp)) { // CanvasScope
drawIntoCanvas {
TextDelegate.paint(canvas = it, layoutResult)
}
}
}
[1] https://kotlinlang.slack.com/archives/CJLTWPH7S/p1611055679272900
[2] https://github.com/androidx/androidx/blob/androidx-main/compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/text/TextFieldDelegateIntegrationTest.ktVipulyaara
02/06/2021, 7:02 PM@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 = AmbientDensity.current,
resourceLoader = object : Font.ResourceLoader {
override fun load(font: Font): Any {
return false
}
}
)
val layoutResult = textDelegate.layout(constraints, LayoutDirection.Ltr)
return if (layoutResult.didOverflowHeight) {
debug { "Delegate text size again $textSize" }
calculateTextSize(constraints, text, textSize - 2.sp)
} else {
debug { "Delegate text size done $textSize" }
textSize
}
}
Denis
02/08/2021, 2:27 PMlayout
call.