Home > other >  How to center Text in Canvas in Jetpack compose?
How to center Text in Canvas in Jetpack compose?

Time:08-15

I am creating a custom composable in Jetpack Compose using Canvas.
How to center text when using drawText?

Code

@OptIn(ExperimentalTextApi::class)
@Composable
fun MyCenterTextInCanvas() {
    val width: Dp = 200.dp
    val height: Dp = 40.dp
    val textMeasurer = rememberTextMeasurer()
    Canvas(
        modifier = Modifier
            .background(Color.LightGray)
            .wrapContentSize(
                align = Alignment.Center,
            )
            .requiredSize(
                width = width,
                height = height,
            ),
    ) {
        drawText(
            textMeasurer = textMeasurer,
            text = "Sample Text",
            topLeft = Offset(
                x = (width / 2).toPx(),
                y = (height / 2).toPx(),
            ),
        )
    }
}

Compose version
jetpackComposeVersion = "1.3.0-alpha02"

UI

enter image description here

CodePudding user response:

You can do it by measuring text and placing it as

@OptIn(ExperimentalTextApi::class)
@Composable
fun MyCenterTextInCanvas() {
    val width: Dp = 200.dp
    val height: Dp = 40.dp
    val textMeasurer = rememberTextMeasurer()

    val textLayoutResult: TextLayoutResult =
        textMeasurer.measure(text = AnnotatedString("Sample Text"))
    val textSize = textLayoutResult.size
    Canvas(
        modifier = Modifier
            .background(Color.LightGray)
            .requiredSize(
                width = width,
                height = height,
            ),
    ) {

        val canvasWidth = size.width
        val canvasHeight = size.height


        drawText(
            textMeasurer = textMeasurer,
            text = "Sample Text",
            topLeft = Offset(
                (canvasWidth - textSize.width) / 2f,
                (canvasHeight - textSize.height) / 2f
            ),
        )
    }
}

enter image description here

  • Related