HelloCW
HelloCW

Reputation: 2325

How can I measure the height and width of a text in Jetpack Compose Canvas?

I'm use Jetpack Compose Canvas to draw a division circle. The min value of the division circle is 20, and the max value of the division circle is 120.

So I write the Code A, and I get the result Image A as expected except the label.

From the Image A, I find the label 0, 20, 40 are on good position, and the label 60, 80, 100, 120 are not on good position.

1: It seems that I need to measure the height and width of a text,then adjust the position of the text, if so, how can I measure the height and width of a text?

2: Is there other way to place these text on apposite position without measurement the height and width of text?

Code A

@Composable
fun setCanvas(maxCountList: MaxCountList<Double>) {
    Canvas(
        modifier = Modifier
    ) {

        val axisPaint = Paint()       
        val textPaint = TextPaint()      

        drawIntoCanvas {

            val orig = MyPoint(size.width / 2, size.height / 2)

            val temp = min(size.height, size.width)
            val radius = temp / 2 - 10

            it.drawCircle(Offset(x = 0f.toX(orig), y = 0f.toY(orig)), radius, axisPaint)

            val lineOffset = 5.0f
            val lineLength = 20.0f
            val labelOffset = 10.0f

            val point1 = radius - lineOffset
            val point2 = radius - lineOffset - lineLength
            val point3 = radius - lineOffset - lineLength - labelOffset

            (0..6).forEach { i ->
                val radians = Math.toRadians(225 - i * 45.0)

                val x1 = point1 * cos(radians).toFloat()
                val x2 = point2 * cos(radians).toFloat()
                val x3 = point3 * cos(radians).toFloat()

                val y1 = point1 * sin(radians).toFloat()
                val y2 = point2 * sin(radians).toFloat()
                val y3 = point3 * sin(radians).toFloat()

                it.drawLine(
                    Offset(x = x1.toX(orig), y = y1.toY(orig)),
                    Offset(x = x2.toX(orig), y = y2.toY(orig)),
                    axisPaint
                )

                val label=(i * 20).toString()
                it.nativeCanvas.drawText(label, x3.toX(orig), y3.toY(orig), textPaint)
            }
        }
    }
}


//Convert X to new coordinate
fun Float.toX(originCoordinate: MyPoint) :Float {
    return originCoordinate.x+this
}

//Convert Y to new coordinate
fun Float.toY(originCoordinate: MyPoint):Float {
    return originCoordinate.y-this
}

class MyPoint (val x:Float, val y: Float)

Image A

enter image description here

Upvotes: 2

Views: 2353

Answers (1)

Related Questions