https://kotlinlang.org logo
#compose
Title
# compose
d

Denis

01/30/2021, 12:18 PM
How do you use
TextDelegate
? 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.
Copy code
@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.kt
v

Vipulyaara

02/06/2021, 7:02 PM
Similar code is working for me (with proper density and constraints though).
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 = 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
    }
}
d

Denis

02/08/2021, 2:27 PM
@Vipulyaara, thank you! I thought for some reason it does the job all by itself inside
layout
call.
13 Views