简体   繁体   中英

Circular draggable slider in jetpack compose

I need to prepare a UI with a circular slider where I can pass value or move drag the pointer to slide in the slider similar to the screenshot attached. 在此处输入图像描述

在此处输入图像描述

How can I achieve it?

Check out the solution in this code on Github. Just replace the angle value in Canvas.

You can check out this quick solution. I have 0 degrees at the right but you can reverse the quadrants to suit your needs.

@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(20.0)
    }

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

                    angle = getRotationAngle(handleCenter, shapeCenter)
                    change.consumeAllChanges()
                }
            }
            .padding(30.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.Yellow,
            startAngle = 0f,
            sweepAngle = angle.toFloat(),
            useCenter = false,
            style = Stroke(20f)
        )

        drawCircle(color = Color.Cyan, 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
}

屏幕截图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM