前言
Compose为我们提供了大量动画API,在这里我只介绍介绍一些比较常用的,有更多需求的可以去官网查看
一、animateContentSize
此方法是可以在控件大小大声改变时触发动画效果
@Composable fun AnimationContentSizeTest(){
var test by remember {mutableStateOf("sd")}
Text(
test,
modifier = Modifier.animateContentSize( //添加动画效果
animationSpec = tween(
durationMillis = 1500, //动画时间持续1.5秒
delayMillis = 1000,//延迟一秒后触发
)
)
.clickable {
test += "sdsdsdsdssdsd"
}
)
}
二、animateSizeAsState
与上方的animateContentSize基本相符
@Composable fun AnimationSizeTest2(){
var sizeChange by remember { mutableStateOf(true) }
var textChange by remember { mutableStateOf("变大") }
val testSize = animateSizeAsState(if (sizeChange) Size(
50f,60f) else Size(300f,300f),
animationSpec = tween(
durationMillis = 2000
)
)
Button(
modifier = Modifier.size(testSize.value.width.dp,testSize.value.height.dp).
clip(if (sizeChange) RectangleShape else CircleShape),
colors = ButtonDefaults.buttonColors(
),
onClick = {
sizeChange = !sizeChange
textChange = if (sizeChange) "变大" else "变小"
},
content = {
Text(textChange)
}
)
}
三、animateColorAsState
给控件颜色的变化添加动画效果
@Composable fun AnimationSizeTest(){
var sizeChange by remember { mutableStateOf(true) }
var textChange by remember { mutableStateOf("变大") }
val textColor = animateColorAsState(
if (sizeChange) Color.Red else Color.Blue,
animationSpec = repeatable(
iterations = 10, //重复次数
animation = tween(
durationMillis = 1000
),
repeatMode = RepeatMode.Restart //重复模式
)
)
Button(
modifier = Modifier.clip(if (sizeChange) RectangleShape else CircleShape),
colors = ButtonDefaults.buttonColors(
backgroundColor = textColor.value
),
onClick = {
sizeChange = !sizeChange
textChange = if (sizeChange) "颜色变化" else "继续变化"
},
content = {
Text(textChange)
}
)
}
四、AnimatedVisibility
此方法与上方用法有些不同,这个需要将需要显示动画的组件包装在此方法内
@Composable fun AnimationVisTest(){
var visiable by remember { mutableStateOf(false) }
Column {
AnimatedVisibility(
visible = visiable
){
Image(
painter = painterResource(com.jz.jetpack2.R.drawable.img_head_icon),
contentDescription = null,
modifier = Modifier.padding(top = 180.dp)
)
}
Button(
onClick = {
visiable = !visiable
},
content = {
Text("切换")
}
)
}
}
总结
本文章只作为平时学习的记录