0

我创建了一条交互式线路,但这可能无关紧要。即使没有交互,这也会产生意想不到的结果:-

@Composable
fun PowerClock() {
    var dynamicAngle by remember { mutableStateOf(90f.toRadians()) }
    val angle by animateFloatAsState(targetValue = dynamicAngle)
    Canvas(
        modifier = Modifier
            .fillMaxHeight()
            .fillMaxWidth()
            .pointerInput(Unit) { //Irrelevent, the results go wrong even without invoking this at all
                coroutineScope {

                    while (true) {
//                        val touchDownPointerId = awaitPointerEventScope { awaitFirstDown().id }
                        detectDragGestures { _, dragAmount ->
                            dynamicAngle += atan(dragAmount.x / dragAmount.y)
                        }
                    }
                }
            }
    ) {
        val length = 500
        val path = Path().apply {
            moveTo(size.width / 2, size.height / 2)
            relativeLineTo(length * cos(angle), length * sin(angle))
        }

        drawPath(path, Color.Blue, style = Stroke(10f))
    }
}

这里有一点预览,

所描绘的一个有趣的行为Cavnas是,看着我的实现,角度应该根据x和变化而y变化,对吧?但实际上, y 被忽略了。我已经对此进行了测试。

这是一个错误Cavnas还是我执行错误?

4

1 回答 1

1

我遵循了这个答案并采用了 Compose 代码:

var touchPosition by remember { mutableStateOf(Offset.Zero) }
Canvas(
    modifier = Modifier
        .fillMaxHeight()
        .fillMaxWidth()
        .pointerInput(Unit) { //Irrelevent, the results go wrong even without invoking this at all
            while (true) {
                detectDragGestures { change, _ ->
                    touchPosition = change.position
                }
            }
        }
) {
    val rect = Rect(Offset.Zero, size)
    val length = 500
    val path = Path().apply {
        moveTo(rect.center.x, rect.center.y)
        val angle = (touchPosition - rect.center).let { atan2(it.y, it.x) }
        relativeLineTo(length * cos(angle), length * sin(angle))
    }

    drawPath(path, Color.Blue, style = Stroke(10f))
}

结果:

于 2021-10-28T10:34:35.873 回答