I am creating a custom clock UI.. there are some c...
# compose
m
I am creating a custom clock UI.. there are some components which will always be on UI(doesn't need to be redrawn one each composition like time hour, the small minute and hour marks) except the minute and hour hand which will be redrawn when user interacts with it to set alarm Attaching the code in threads
Copy code
Canvas(
    modifier = Modifier
        .fillMaxSize()
        .align(Alignment.Center)
        .clip(CircleShape)
        .background(Color.Yellow)
        .clipToBounds()
        .pointerInput(Unit) {
            detectDragGestures { change, dragAmount ->
                clickCoordinate = Offset(change.position.x, change.position.y)

            }
            detectTapGestures {
                clickCoordinate = it
            }
        }
) {
    val size = this.size

    val centerX = size.width * 0.5f
    val centerY = size.height * 0.5f

    val radius = size.width * 0.5f

    val angle = calculateAngle(
        center = Offset(x = centerX, y = centerY),
        point = Offset(x = clickCoordinate.x, y = clickCoordinate.y)
    )

    val pointOnCircle = calculatePointOnCircumference(
        Offset(x = centerX, y = centerY),
        radius,
        angle
    )

    for (i in 0 until 12) {
        val angle2 = (i * 30).toFloat()
        val pointOnCircumference =
            calculatePointOnCircumference2(center, radius, angle2)

        drawLine(
            color = Color.Gray,
            start = center,
            end = pointOnCircumference
        )
    }

    for (i in 0 until 60) {
        val minute = (i * 6).toFloat()
        val pointOnCircumference =
            calculatePointOnCircumference2(center, radius, minute)

        val isMultipleOf5 = (i % 5 == 0)

        drawLine(
            color = Color.Gray,
            start = pointOnCircumference,
            end = calculatePointOnCircumference2(
                center,
                radius - if (isMultipleOf5) 24f else 16f,
                minute
            ),
            strokeWidth = if (isMultipleOf5) 8f else 4f
        )
    }
}
the minute and hour marks will always be there on UI...how to just draw it once
s
You need to draw the entire canvas on each draw. You could put the static elements in a bitmap and draw that, but it's probably not any more efficient. Is there a problem with drawing them each time?
m
I was just thinking to avoid it because its the same thing again and again
As you can see, only the hour/minutes hands will change... Rest all is same
s
It needs to be redrawn because the hands change.
m
Shall I keep 2 canvas? one within the other only the canvas containing the hands will redraw
s
It seems too complicated to me. If there's no performance problem, I wouldn't worry about it.
☝🏻 1
☝️ 1