如何在 Jetpack compose 中将画布中的文本居中?

Abh*_*bhi 4 android android-jetpack-compose android-jetpack-compose-canvas

我正在使用 Canvas 在 Jetpack Compose 中创建自定义可组合项。
使用时如何让文字居中drawText

代码

@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(),
            ),
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

撰写版本
jetpackComposeVersion = "1.3.0-alpha02"

用户界面

在此输入图像描述

Thr*_*ian 11

您可以通过测量文本并将其放置为

@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
            ),
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 谢谢。。我不知道如何使用文本测量器。 (2认同)
  • 尽管居中逻辑是正确的,但请不要在构图中测量文本。理想情况下,文本测量应该是布局阶段的一部分。此外,测量的文本应该被记住/缓存。您可以在 Box 上使用 Modifier.drawWithCache 而不是 Canvas 可组合项来缓存 `TextLayoutResult`。如果你检查 Canvas 的源代码,你会发现它没有什么特别的。无论如何,TextMeasurer 默认会在内部缓存结果。如果属性没有改变,文本布局将被跳过,结果将从内部缓存返回。 (2认同)
  • @HalilIbrahimOzer可以肯定,画布只不过是带有 Modifier.drawContent 的 Spacer,但是我们如何将文本测量移动到布局阶段?在这个答案中,我移动了要记住的文本测量。/sf/answers/5148326781/。它是否正确?另外,您介意发布带有布局阶段和“Modifier.drawWithCache”的示例吗? (2认同)