[英]How to implement a translate + scale animation in Jetpack Compose?
我有一個屏幕,屏幕的一個角有一個圖像,我想將它設置為屏幕中心的動畫。 有點像從
Icon(
painter = //,
contentDescription = //,
modifier = Modifier.size(36.dp)
)
到
Icon(
painter = //,
contentDescription = //,
modifier = Modifier.fillMaxSize()
)
第一個位於屏幕的左上角,第二個位於中心。 如何在兩個狀態之間設置動畫?
要使動畫在 Compose 中工作,您需要為某個特定修飾符的值設置動畫。 您無法在不同的修改器集之間設置動畫。
在此文檔段落之后,您可以為Modifier.size
設置動畫值。
要確定第一I等待圖像的大小,與該值的size
改性劑可以被設置(我用then
用空的Modifier
之前),然后該值可以是動畫。
這是一個示例:
val animatableSize = remember { Animatable(DpSize.Zero, DpSize.VectorConverter) }
val (containerSize, setContainerSize) = remember { mutableStateOf<DpSize?>(null) }
val (imageSize, setImageSize) = remember { mutableStateOf<DpSize?>(null) }
val density = LocalDensity.current
val scope = rememberCoroutineScope()
Button(onClick = {
scope.launch {
if (imageSize == null || containerSize == null) return@launch
val targetSize = if (animatableSize.value == imageSize) containerSize else imageSize
animatableSize.animateTo(
targetSize,
animationSpec = tween(durationMillis = 1000)
)
}
}) {
Text("Animate")
}
Box(
Modifier
.padding(20.dp)
.size(300.dp)
.fillMaxSize()
.background(Color.LightGray)
.onSizeChanged { size ->
setContainerSize(
with(density) { size.toSize().toDpSize() }
)
}
) {
Image(
Icons.Default.PriorityHigh,
contentDescription = null,
modifier = Modifier
.then(
Modifier.run {
if (animatableSize.value != DpSize.Zero) {
size(animatableSize.value)
} else {
this
}
}
)
.onSizeChanged { size ->
if (imageSize != null) return@onSizeChanged
val dpSize = with(density) { size.toSize().toDpSize() }
setImageSize(dpSize)
scope.launch {
animatableSize.snapTo(dpSize)
}
}
)
}
結果:
像這樣簡單的事情:
@Composable
fun DUM_E(){
val modifier = Modifier.animateContentSize()
Icon(
modifier =
if(triggered) modifier.fillMaxSize()
else modifier.size(36.dp)
)
}
如果您還想為偏移設置動畫,只需在下面發表評論,我可能會修改答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.