Compose 动画入门 (一) : animateXxxAsState 实现放大/缩小/渐变等效果

1. 前言

动画Android Compose中很重要的一块内容。利用Compose可以简洁地定义动画,我们可以轻松快速地通过动画让应用变得生动有趣。
本文会介绍如何定义一个最简单的Compose动画,从而实现Compose动画。

1.1 定义一个Box

首先,我们先定义一个Box,给它背景设置为蓝色

Box(Modifier.size(50.dp).background(Color.Blue)) {
    
    

}

显示效果如下
在这里插入图片描述
这样我们就把方块显示出来了,接下来怎么让方块放大呢 ?

1.2 定义一个Size替换50.dp

定义一个变量size,将50.dp替换为变量size。可以看到size是用mutableStateOf进行包裹的,mutableStateOf的返回值是一个MutableState,通过它就可以实现值变化后,Compose界面自动改变。

var size by remember {
    
    
    mutableStateOf(50.dp)
}

Box(
    Modifier
        .size(size)
        .background(Color.Blue)) {
    
    

}

1.3 设置点击事件改变size大小

通过点击事件,改变变量Size的值,这样Compose会自动改变界面。

var size by remember {
    
    
    mutableStateOf(50.dp)
}

Box(
    Modifier
        .size(size)
        .background(Color.Blue)
        .clickable {
    
    
            size = if (size == 50.dp) 100.dp else 50.dp
        }) {
    
    

}

我们运行项目,点击后效果如下
在这里插入图片描述

1.4 实现动画效果

刚才实现的效果是瞬间变大的,我们希望动画是有一个渐变的过程的。
这就需要使用到animateDpAsState()

我们将

var size by remember {
    
    
    mutableStateOf(50.dp)
}

替换为

var big by remember {
    
    
    mutableStateOf(false)
}
val size by animateDpAsState(if (big) 100.dp else 50.dp)

然后,在点击事件的时候,去改变big的值

Box(
    Modifier
        .size(size)
        .background(Color.Blue)
        .clickable {
    
    
            big = !big
        }) {
    
    

}

运行程序,来看下效果
在这里插入图片描述

1.5 更多的animateXxxAsState

Compose中不光有animateDpAsState(),还有

  • animateValueAsState : 其他的animateXxxAsState内部都是调用的这个
  • animateRectAsState : 参数是传的一个Rect对象,Rect(left,top,right,bottom)
  • animateIntAsState : 参数传的是Int
  • animateDpAsState : 参数传的是Dp
  • animateFloatAsState : 参数传的是Float
  • animateColorAsState : 参数传的是Color
  • animateOffsetAsState : 参数传的是OffsetOffset(x,y)xyFloat类型
  • animateIntOffsetAsState : 参数传的是IntOffsetIntOffset(x,y)xyInt类型
  • animateSizeAsState : 参数传的是SizeSize(width,height)widthheightFloat类型
  • animateIntSizeAsState : 参数传的是IntSizeIntSize(width,height)widthheightInt类型

1.6 animateColorAsState

我们以animateColorAsState为例,来试一下

var big by remember {
    
    
    mutableStateOf(false)
}
val size by animateDpAsState(if (big) 100.dp else 50.dp)
val color by animateColorAsState(targetValue = if (big) Color.Red else Color.Blue)

Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
    
    
    Box(
        Modifier
            .size(size)
            .background(color)
            .clickable {
    
    
                big = !big
            }) {
    
    

    }
}

可以看到,使用方式是一样的,效果如下所示
在这里插入图片描述

1.7 小结

到这儿,我们就已经学会如何使用animateXXAsState来实现Compose动画了。
但想必大家还有疑问

  • 为什么animateDpAsState要用val ? 而mutableStateOf就用var ?
  • MutableStateState有什么区别 ?
  • 为什么animateDpAsState不需要包remember ?
  • 为什么把mutableStateOf替换为animateDpAsState,就可以实现动画渐变的效果 ?

这些我们都将在下一篇文章里介绍。

Compose 动画入门 (二) : 为什么animateDpAsState要用val ? MutableState和State有什么区别 ?

猜你喜欢

转载自blog.csdn.net/EthanCo/article/details/128601647