Jetpack Compose 实现渐显爱心

首先实现红色爱心图标

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)。

知识点

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

效果图

请添加图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

九狼JIULANG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值