我正在尝试在 Jetpack compose 中实现翻译动画,但我无法找到合适的源。任何人都可以帮助我在 jetpack compose 中实现翻译动画,我可以在其中手动设置开始和编辑位置..
jetpack compose 中平移动画的替代方案是 OFFSET ANIMATION 是的,我可以通过偏移动画来实现这一点。我将在下面分享代码并详细注释,以便读者更容易理解它
val coroutineScope = rememberCoroutineScope()
val offsetX = remember { Animatable(0f) }
val offsetY = remember { Animatable(0f) }
Image(
painter = rememberDrawablePainter(
ContextCompat.getDrawable(
context,
R.drawable.image
)
),
contentDescription = "image",
contentScale = ContentScale.Crop,
modifier = Modifier
.offset {
IntOffset(
offsetX.value.toInt(),
offsetY.value.toInt()
)
}
.width(300.dp)
.height(300.dp)
)
// Finally run the animation on clicking a button or whenever you want to start it.
coroutineScope.launch {
launch {
offsetXFirst.animateTo(
targetValue = targetValue,
animationSpec = tween(
durationMillis = 2000,
delayMillis = 0
)
)
}
launch {
offsetYFirst.animateTo(
targetValue = size.height.toFloat(),
animationSpec = tween(
durationMillis = 2000,
delayMillis = 0
)
)
}
}
如果您的目标是通过翻译动画显示/隐藏一些可组合项,最好的方法是使用
AnimatedVisibility
:
AnimatedVisibility(
visible = isVisible,
enter = slideInVertically { it },
exit = slideOutVertically { it }
) {
SomeComposable()
}
此外,还有一个关于如何在 Jetpack Compose 中选择合适动画的好方案:https://developer.android.com/jetpack/compose/animation
只是插话讨论。正如其他人所说,使用
offset
修饰符是将某些翻译应用于元素的最快方法。
但是,
offset
修饰符仅影响正在显示的内容,而不影响元素的实际尺寸测量。
如果您根据另一个元素 A
的位置来偏移元素 B
,则无论将 B
应用于元素 .offset
,元素 A
的位置都将保持不变。这通常意味着您将留下一些空白空间。
为了解决这个问题,可以使用 .graphicsLayer { translationY = translationYPx }
modifier应用实际的 translation。
总而言之,请尽可能使用
.offset
modifier,因为它效率更高,并且仅当您需要元素的大小在离开屏幕时也发生变化时才使用 .graphicsLayer
。
使用偏移也是我的解决方案。然而使用 animateDpAsState 代替。标签指示器在 x 轴上移动:
val offsetState = animateDpAsState(targetValue = targetPositionDp)
Box(modifier = Modifier
.offset(offsetState.value, 0.dp)
.background(color = Color.Red)
.size(tabWidth, tabHeight))