如何使用Android Jetpack Compose显示触摸点?

4
如何使用Android Jetpack Compose显示触摸点?
示例:
enter image description here

你看过Modifier.pointerInput了吗? - Rafsanjani
1个回答

8

这是我的解决方案。

@Composable
fun TouchableFeedback() {
    // Some constants here
    val sizeAnimationDuration = 200
    val colorAnimationDuration = 200
    val boxSize = 100.dp
    val startColor = Color.Red.copy(alpha = .05f)
    val endColor = Color.Red.copy(alpha = .8f)
    // These states are changed to update the animation
    var touchedPoint by remember { mutableStateOf(Offset.Zero) }
    var visible by remember { mutableStateOf(false) }

    // circle color and size in according to the visible state
    val colorAnimation by animateColorAsState(
        if (visible) startColor else endColor,
        animationSpec = tween(
            durationMillis = colorAnimationDuration,
            easing = LinearEasing
        ),
        finishedListener = {
            visible = false
        }
    )
    val sizeAnimation by animateDpAsState(
        if (visible) boxSize else 0.dp,
        tween(
            durationMillis = sizeAnimationDuration,
            easing = LinearEasing
        )
    )
    // Box for the whole screen
    Box(
        Modifier
            .fillMaxSize()
            .pointerInput(Unit) {
                detectTapGestures {
                    // changing the state to set the point touched on the screen
                    // and make it visible
                    touchedPoint = it
                    visible = true
                }
            }
    ) {
        // The touch offset is px and we need to convert to Dp
        val density = LocalDensity.current
        val (xDp, yDp) = with(density) {
            (touchedPoint.x.toDp() - boxSize / 2) to (touchedPoint.y.toDp() - boxSize / 2)
        }
        // This box serves as container. It has a fixed size.
        Box(
            Modifier
                .offset(xDp, yDp)
                .size(boxSize),
        ) {
            // And this box is animating the background and the size
            Box(
                Modifier
                    .align(Alignment.Center)
                    .background(colorAnimation, CircleShape)
                    .height(if (visible) sizeAnimation else 0.dp)
                    .width(if (visible) sizeAnimation else 0.dp),
            )
        }
    }
}

这是结果:

输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接