https://kotlinlang.org logo
#compose
Title
# compose
a

Ankit Shah

12/21/2021, 11:07 AM
Hello everyone, I am working on a custom circular slider on jetpack compose, and with help some resources I was able to do it at some extent. But the problem is that it starts from 3'0 Clock. I want it to start from 12'O Clock. Can someone help me with this small tweak? I have replied the code in the thread
Copy code
@Composable
fun Content() {
    var radius by remember {
        mutableStateOf(0f)
    }

    var shapeCenter by remember {
        mutableStateOf(Offset.Zero)
    }

    var handleCenter by remember {
        mutableStateOf(Offset.Zero)
    }

    var angle by remember {
        mutableStateOf(0.0)
    }

    Canvas(
            modifier = Modifier
                    .fillMaxSize()
                    .pointerInput(Unit) {
                        detectDragGestures { change, dragAmount ->
                            handleCenter += dragAmount

                            angle = getRotationAngle(handleCenter, shapeCenter)
                            change.consumeAllChanges()
                        }
                    }
                    .padding(20.dp)

    ) {
        shapeCenter = center

        radius = size.minDimension / 2

        val x = (shapeCenter.x + cos(Math.toRadians(angle)) * radius).toFloat()
        val y = (shapeCenter.y + sin(Math.toRadians(angle)) * radius).toFloat()

        handleCenter = Offset(x, y)

        drawCircle(color = Color.Black.copy(alpha = 0.10f), style = Stroke(20f), radius = radius)
        drawArc(
                color = Color(0xff0fa1a0),
                startAngle = 0f,
                sweepAngle = angle.toFloat(),
                useCenter = false,
                style = Stroke(20f)
        )

        drawCircle(color = Color(0xff0fa1a0), center = handleCenter, radius = 60f)
    }
}

private fun getRotationAngle(currentPosition: Offset, center: Offset): Double {
    val (dx, dy) = currentPosition - center
    val theta = atan2(dy, dx).toDouble()

    var angle = Math.toDegrees(theta)

    if (angle < 0) {
        angle += 360.0
    }
    return angle
}
I tried by tweaking the startAngle = 0f to 270f, which starts at 12'O clock but only the arc seems to work not the circle
m

Md. Nazmun Sadat Khan

12/21/2021, 4:04 PM
I haven't read it too deeply, but why not add 270 to the angle too when you calculating the coordinates for
handleCenter
?
a

Ankit Shah

12/21/2021, 4:06 PM
yes, actually I tried that as well but unknowingly it makes code behave really bad, like no sync of circle and pointer
60 Views