Thread
#compose
    d

    Denis

    1 year ago
    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.
    @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
    Vipulyaara

    Vipulyaara

    1 year ago
    Similar code is working for me (with proper density and constraints though).
    @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

    1 year ago
    @Vipulyaara, thank you! I thought for some reason it does the job all by itself inside
    layout
    call.