32. Compose 优美的触摸动画

109 阅读1分钟
@Composable
fun TouchAnimationPage(navCtrl: NavHostController, title: String) {

    val currentPositionColor = Color.White
    val lastPositionColor = Color.LightGray
    var cacheOffset by remember() {
        mutableStateOf(Offset.Zero)
    }

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

    val animatedOffset = remember {
        Animatable(Offset(0f, 0f), Offset.VectorConverter)
    }
    val pxValue = with(LocalDensity.current) { 40.dp.toPx() } / 2f

    CommonToolbar(navCtrl, title) {
        Box(modifier = Modifier
            .fillMaxSize()
            .background(color = Color.Magenta)
            .pointerInput(Unit) {
                coroutineScope {
                    while (true) {
                        val offset = awaitPointerEventScope {
                            awaitFirstDown().position
                        }
                        lastOffset = cacheOffset
                        cacheOffset = offset
                        launch {
                            animatedOffset.animateTo(
                                offset,
                                animationSpec = spring(stiffness = Spring.StiffnessLow)
                            )
                        }
                    }
                }
            }
            .drawBehind {
                drawCircle(color = currentPositionColor, radius = pxValue, center = cacheOffset)
                drawCircle(color = lastPositionColor, radius = pxValue, center = lastOffset)
            }
        ) {
            Box(
                Modifier
                    .offset {
                        IntOffset(
                            (animatedOffset.value.x - pxValue).roundToInt(),
                            (animatedOffset.value.y - pxValue).roundToInt()
                        )
                    }
                    .size(40.dp)
                    .background(MaterialTheme.colors.primary, CircleShape)
            )
        }
    }
}