Jetpack Compose 实现渐显爱心

720 阅读2分钟

「这是我参与2022首次更文挑战的第3天,活动详情查看:2022首次更文挑战

首先实现红色爱心图标

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还可用于将效果应用于
缩放scaleXscaleY
旋转(rotationX、rotationY、rotationZ)
不透明度(alpha)
阴影(shadowElevation、shape)
剪裁(clip、shape)。

知识点

alpha = remember { mutableStateOf() } remember 和 mutableStateOf在Jetpack Compose 教你打造一个会动的按钮说过
remember保持数据状态,mutableStateOf监听状态变化

LaunchedEffect是什么?

当LaunchedEffect进入构图时,它会将块启动到构图的CoroutineContext中。当使用不同的键1重新组合LaunchedEffect时,协同程序将被取消并重新启动。当LaunchedEffect离开构图时,协同程序将被取消。 此函数不应用于(重新)启动正在进行的任务,以通过将回调数据存储在传递给key1的可变状态来响应回调事件。相反,请参阅rememberCoroutineScope以获取一个CoroutineScope,该CoroutineScope可用于启动作用域为合成的正在进行的作业,以响应事件回调。

简单来说就是:LaunchedEffect就是能让你在Composable中使用协程。

LaunchedEffect简单使用

@Composable
fun SplashScreen(
    onTimeOut: () -> Unit
) {
    LaunchedEffect(Unit) { 
        delay(SplashWaitTime)
        onTimeOut()
    }
    ...
}

实现渐显动画

    animate(
        initialValue = 1f,
        targetValue = 0f,
        animationSpec = infiniteRepeatable(
            animation = tween(1000),
            repeatMode = RepeatMode.Reverse
        )
    )

animate作用就是
基于目标的动画,使用可选的initialVelocity从给定的initialValue向targetValue设置动画。initialVelocity默认为0f。默认情况下,弹簧将用于动画。可以提供替代animationSpec来替换默认弹簧。在每个帧上,将使用最新的值和速度调用块。

利用alpha在animate里实现 initialValue = 1f targetValue = 0f

infiniteRepeatable
创建一个无限重复表规范,该规范将播放DurationBasedAnimationSpec(例如TweenSpec、KeyframeResSpec)无限次的迭代。 repeatMode—动画是从开始(即repeatMode.Restart)或者从结束(即repeatMode.Reverse)开始重复

我们用infiniteRepeatable来写,同样达到死循环的效果,并且加了动画渐变。 tween()用来设置动画时间单位毫秒

完整代码

@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
        )
    }
}

效果图

ezgif.com-gif-maker (1).gif

觉得对你有帮助就点个赞叭