5

如何在切换到特定状态时使用协程播放复杂动画?

@Composable
fun SomeView(viewModel: SomeViewModel) {
    val state by viewModel.stateFlow.collectAsState()
    val scope = rememberCoroutineScope()
    
    ...
    val shutterAlpha by remember { mutableStateOf(0f) }
    Box(modifier = Modifier
        .fillMaxSize()
        .alpha(shutterAlpha)
        .background(Color.Black)
    )

    val transition = updateTransition(targetState = state, label = "label")
    <on transitioning to CaptureState> { // need actual condition check code here
        scope.launch {
            animate(0f, 1f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
            animate(1f, 0f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
        }
    }
}
4

1 回答 1

2

LaunchedEffect是答案:

@Composable
fun SomeView(viewModel: SomeViewModel) {
    val state by viewModel.stateFlow.collectAsState()
    
    ...
    val shutterAlpha by remember { mutableStateOf(0f) }
    Box(modifier = Modifier
        .fillMaxSize()
        .alpha(shutterAlpha)
        .background(Color.Black)
    )

    LaunchedEffect(state) {
        if (state == CaptureState) {
            animate(0f, 1f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
            animate(1f, 0f, animationSpec = tween(150)) { value, _ -> shutterAlpha = value }
        }
    }
}
于 2021-11-17T09:25:25.667 回答