简体   繁体   中英

How to center Text in Canvas in Jetpack compose?

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

在此处输入图像描述

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
            ),
        )
    }
}

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM