使用 animate*AsState
为单个值添加动画效果
`animate*AsState`\] 函数是 Compose 中最简单的动画 API,用于为单个值添加动画效果。您只需提供目标值(或结束值),该 API 就会从当前值开始向指定值播放动画。
下面举例说明了如何使用此 API 为 alpha 添加动画效果。只需将目标值封装在 \[`animateFloatAsState`\] 中,alpha 值就会是所提供值(在本例中为 `1f` 或 `0.5f`)之间的动画值。

```ts
@Composable
private fun example1() {
val enabled = remember { mutableStateOf(true) }
val alpha = animateFloatAsState(if (enabled.value) 1f else 0.5f,
label = "animateFloatAsState",
animationSpec = tween(durationMillis = 800)
)
Column {
customTitle(title = "使用 animate*AsState 为单个值添加动画效果")
Button(modifier = Modifier.padding(start = 15.dp), onClick = { enabled.value = !enabled.value }) {
Text(text = if (enabled.value) "半透明" else "非透明")
}
Box(
Modifier.fillMaxWidth()
.height(200.dp)
.graphicsLayer(alpha = alpha.value)
.background(Color.Red)
)
}
}
```
## 使用 Transition 同时为多个属性添加动画效果
### 将过渡效果与 `AnimatedVisibility` 和 `AnimatedContent` 搭配使用

```ts
@OptIn(ExperimentalAnimationApi::class)
@Composable
private fun example2() {
val selected = remember { mutableStateOf(false) }
// Animates changes when `selected` is changed.
val transition = updateTransition(selected.value, label = "selected state")
val borderColor = transition.animateColor(label = "border color") { isSelected ->
if (isSelected) Color.Magenta else Color.White
}
val elevation = transition.animateDp(label = "elevation") { isSelected ->
if (isSelected) 10.dp else 2.dp
}
Column {
customTitle(title = "使用 animate*AsState 为单个值添加动画效果")
Surface(
shape = RoundedCornerShape(8.dp),
border = BorderStroke(2.dp, borderColor.value),
shadowElevation = elevation.value,
modifier = Modifier.padding(all=5.dp).clickable {
selected.value = !selected.value
}
) {
Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) {
Text(text = "Hello, world!")
// AnimatedVisibility 过渡
transition.AnimatedVisibility(
visible = { targetSelected -> targetSelected },
enter = expandVertically(),
exit = shrinkVertically()
) {
Text(text = "It is fine today.")
}
// AnimatedContent 过渡
transition.AnimatedContent { targetState ->
if (targetState) {
Text(text = "Selected")
} else {
Icon(imageVector = Icons.Default.Phone, contentDescription = "Phone")
}
}
}
}
CodeView(assetUrl = "animation/animationValue/code1.txt", modifier = Modifier.padding(top = 10.dp))
}
}
```
### 封装 Transition 并使其可重复使用

```ts
@Composable
private fun example3() {
val boxState = remember {
mutableStateOf(BoxState.Collapsed)
}
val transitionData = updateTransitionData(boxState.value)
Column {
customTitle(title = "使用 animate*AsState 为单个值添加动画效果")
Box(
modifier = Modifier
.background(transitionData.color.value)
.size(transitionData.size.value).clickable {
if (boxState.value == BoxState.Collapsed) {
boxState.value = BoxState.Expanded
} else {
boxState.value = BoxState.Collapsed
}
}
)
}
}
enum class BoxState { Collapsed, Expanded }
// 保存动画的值 the animation values.
private data class TransitionData(
val color: State