Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save canwe/cbbf175ef81f9d2ccd1c8a1c1e95de8b to your computer and use it in GitHub Desktop.
Save canwe/cbbf175ef81f9d2ccd1c8a1c1e95de8b to your computer and use it in GitHub Desktop.
Flying Hearts Animation in jetpack Compose
@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,
)
}
)
}
}
@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