How to draw text in Jetpack compose at the center of another object? – Android

by
Ali Hasan
android android-canvas android-jetpack-compose android-jetpack-compose-canvas drawtext

Quick Fix: You can get TextLayoutResult which returns the size of the rectangle that text is contained. Andy by offsetting half of the width to the left and half of the height to the top, you can center text inside the Canvas.

The Problem:

Given the center of a circle and the text you want to draw, how can you draw that text exactly at the center of the circle in Jetpack Compose?

The Solutions:

Solution 1: Calculate Text Size and Offset

  • Utilize the TextMeasurer to determine the size of the text rectangle.

  • Calculate the offset by subtracting half the text width and height from the center coordinates of the circle.

  • Pass this calculated Offset as the topLeft argument in the drawText function, which will center the text within the circle.

val textMeasurer = rememberTextMeasurer()

val textLayoutResult = remember(textToDraw, style) {
    textMeasurer.measure(textToDraw, style)
}

Canvas(modifier = Modifier.fillMaxSize()) {
    ...

    drawText(
        textMeasurer = textMeasurer,
        text = textToDraw,
        style = style,
        topLeft = Offset(
            x = center.x - textLayoutResult.size.width / 2,
            y = center.y - textLayoutResult.size.height / 2,
        )
    )
    ...
}

Q&A

How to draw text inside a circle in Jetpack Compose at the center of another object?

You can get TextLayoutResult which returns size of the rectangle that text is contained. Andy by offsetting half of the width to left and half of the height to top you can center text inside Canvas.

How to draw the text automatically at the center of the circle?

Use TextLayoutResult which returns size of the rectangle that text is contained. Andy by offsetting half of the width to left and half of the height to top you can center text inside Canvas.

Video Explanation:

The following video, titled "Canvas Basics in Jetpack Compose - Android Studio Tutorial ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Want to learn everything there is about canvas? Get the Canvas Masterclass here: ...