Flying Hearts Animation in jetpack Compose
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@OptIn(ExperimentalAnimationApi::class) | |
@Composable | |
fun Heart(modifier: Modifier, horizontalPadding: Int, bottomMargin: Int) { | |
val width = LocalConfiguration.current.screenWidthDp | |
val height = LocalConfiguration.current.screenHeightDp - bottomMargin | |
val yRandom = Random.nextInt(0, height / 2) | |
val xRandom = Random.nextInt(horizontalPadding, (width - horizontalPadding)) | |
val state = remember { | |
mutableStateOf(HeartState.Show) | |
} | |
val offsetYAnimation: Dp by animateDpAsState( | |
targetValue = when (state.value) { | |
HeartState.Show -> height.dp | |
else -> yRandom.dp | |
}, | |
animationSpec = tween(1000) | |
) | |
val offsetXAnimation: Dp by animateDpAsState( | |
targetValue = when (state.value) { | |
HeartState.Show -> (((width - (horizontalPadding * 2)) / 2) + 8).dp | |
else -> xRandom.dp | |
}, | |
animationSpec = tween(1000) | |
) | |
LaunchedEffect(key1 = state, block = { | |
state.value = when (state.value) { | |
HeartState.Show -> HeartState.Hide | |
HeartState.Hide -> HeartState.Show | |
} | |
}) | |
AnimatedVisibility( | |
visible = state.value == HeartState.Show, | |
enter = fadeIn(animationSpec = tween(durationMillis = 250)), | |
exit = fadeOut(animationSpec = tween(durationMillis = 700)) | |
) { | |
Canvas(modifier = modifier | |
.offset(y = offsetYAnimation, x = offsetXAnimation), | |
onDraw = { | |
val path = Path().apply { | |
heartPath(Size(120f, 120f)) | |
} | |
drawPath( | |
path = path, | |
color = Color.Red, | |
) | |
} | |
) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Composable | |
fun Screen() { | |
val heartCount = remember { mutableStateOf(0) } | |
Box(modifier = Modifier.fillMaxSize()) { | |
repeat(heartCount.value) { | |
Heart( | |
modifier = Modifier | |
.fillMaxSize() | |
.align(Alignment.BottomCenter) | |
.padding(bottom = 36.dp), | |
horizontalPadding = 24, | |
bottomMargin = 110 | |
) | |
} | |
Button( | |
onClick = { | |
heartCount.value++ | |
}, | |
modifier = Modifier | |
.align(Alignment.BottomCenter) | |
.padding(24.dp) | |
.wrapContentHeight() | |
.wrapContentWidth() | |
) { | |
Text( | |
text = "Like", | |
color = Color.White | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment