首先实现红色爱心图标
Box() {
Icon(
Icons.Filled.Favorite,
contentDescription = null,
modifier = Modifier
.align(Alignment.Center)
.graphicsLayer(
scaleX = 3.0f,
scaleY = 3.0f,
alpha = alpha.value
),
tint = Color.Red
)
}
Icons.Filled是compose自带的图标库,可以直接用
graphicsLayer
修饰语。使内容绘制到绘制层中的元素。绘制层可以与父层分开失效。当内容独立于上面的任何内容进行更新时,应使用graphicsLayer以最小化无效内容。
graphicsLayer还可用于将效果应用于
缩放(scaleX
、scaleY
)
旋转(rotationX、rotationY、rotationZ)
不透明度(alpha)
阴影(shadowElevation、shape)
剪裁(clip、shape)。
知识点
remember 和 mutableStateOf在Jetpack Compose 教你打造一个会动的按钮说过
LaunchedEffect是什么?
当LaunchedEffect进入构图时,它会将块启动到构图的CoroutineContext中。当使用不同的键1重新组合LaunchedEffect时,协同程序将被取消并重新启动。当LaunchedEffect离开构图时,协同程序将被取消。
此函数不应用于(重新)启动正在进行的任务,以通过将回调数据存储在传递给key1的可变状态来响应回调事件。相反,请参阅rememberCoroutineScope以获取一个CoroutineScope,该CoroutineScope可用于启动作用域为合成的正在进行的作业,以响应事件回调。
简单来说就是:LaunchedEffect就是能让你在Composable中使用协程。
LaunchedEffect简单使用
@Composable
fun SplashScreen(
onTimeOut: () -> Unit
) {
LaunchedEffect(Unit) {
delay(SplashWaitTime)
onTimeOut()
}
...
}
实现渐显动画
val alpha = remember { mutableStateOf(1f) }
LaunchedEffect(Unit) {
animate(
initialValue = 1f,
targetValue = 0f,
animationSpec = infiniteRepeatable(
animation = tween(1000),
repeatMode = RepeatMode.Reverse
)
) { value, _ ->
alpha.value = value
}
}
利用alpha在animate里实现
initialValue = 1f
targetValue = 0f
完整代码
@Composable
fun LoveAnimation() {
val alpha = remember { mutableStateOf(1f) }
LaunchedEffect(Unit) {
animate(
initialValue = 1f,
targetValue = 0f,
animationSpec = infiniteRepeatable(
animation = tween(1000),
repeatMode = RepeatMode.Reverse
)
) { value, _ ->
alpha.value = value
}
}
Box(Modifier.fillMaxSize()) {
Icon(
Icons.Filled.Favorite,
contentDescription = null,
modifier = Modifier
.align(Alignment.Center)
.graphicsLayer(
scaleX = 3.0f,
scaleY = 3.0f,
alpha = alpha.value
),
tint = Color.Red
)
}
}