0

我希望val label="100"在 X 轴附近放置一个文本,所以我使用代码it.nativeCanvas.drawText(label, orignX- 40f, canvasHeight, textPaint)来实现。

我运行代码 A,得到结果 Image A。

但是我不知道如何测量文本的宽度,所以我不得不不断测试,最后我使用近似值orignX- 40f,但这不是一个好方法。

使用 Jetpack Compose 时如何测量文本宽度?

代码 A

@Composable
fun setCanvas() {
    Canvas(
        modifier = Modifier
            .fillMaxSize()
            .padding(2.dp)
    ) {
        val orignX = 100f
        val origY = 100f
        val canvasWidth = size.width-orignX
        val canvasHeight = size.height-origY

        val axisPaint = Paint()
        axisPaint.isAntiAlias = true
        axisPaint.style = PaintingStyle.Stroke
        axisPaint.strokeWidth = 2f
        axisPaint.color = Color.Blue

        val textPaint = TextPaint()
        textPaint.isAntiAlias = true
        textPaint.color = Color.Red.toArgb()
        textPaint.textSize = 15f

        drawIntoCanvas {
            it.drawLine(
                Offset(x = orignX, y = canvasHeight),
                Offset(x = canvasWidth, y = canvasHeight),
                axisPaint
            )

            it.drawLine(
                Offset(x = orignX, y = origY),
                Offset(x = orignX, y = canvasHeight),
                axisPaint
            )

            val label="100"
            it.nativeCanvas.drawText(label, orignX- 40f, canvasHeight, textPaint)
        }

    }

}

图像 A

在此处输入图像描述

4

0 回答 0