Is there a way to draw centered text on canvas? I ...
# compose-desktop
i
Is there a way to draw centered text on canvas? I can find solution in Android compose. but on the desktop, the
Paint
class is different
👀 1
a
If you don't need to finely control how the text is drawn, you can do something like this.
Copy code
Text(
    text = "Text",
    modifier = Modifier.fillMaxWidth().drawWithCache {
        onDrawWithContent {
            // Draw under text
            drawContent()
            // Draw above text
        }
    },
    textAlign = TextAlign.Center
)
i
Thanks for your reply. But I need to draw a chart.so text is important 😂
t
I think there is no solution for CfD. I also created a chart and i draw the Text using normal composables on top of the Canvas.
I developed a Modifier to position the text labels at the correct position:
Copy code
fun Modifier.XLabelCenter(
    xPos: Float, yOffset: Float
) = Modifier.layout { measurable, constraints ->
    val placeable = measurable.measure(constraints)
    layout(placeable.width, placeable.height) {
        placeable.place((xPos - (placeable.width / 2f)).toInt(), yOffset.toInt())
    }
}

fun Modifier.YLabelCenter(
    yPos: Float, xOffset: Float
) = Modifier.layout { measurable, constraints ->
    val placeable = measurable.measure(constraints)
    layout(placeable.width, placeable.height) {
        placeable.place(xOffset.toInt(), (yPos - (placeable.height / 2f)).toInt())
    }
}
s
Native canvas does have a drawString method on canvas - https://kotlinlang.slack.com/archives/C01D6HTPATV/p1616399026122500?thread_ts=1616312597.091600&cid=C01D6HTPATV . This is working on CFD
👍 1