如何在Jetpack Compose中实现动画翻译



我试图在Jetpack compose中实现翻译动画,但我找不到合适的来源。有人能帮我在jetpack中实现翻译动画吗?我可以手动设置开始和结束位置。。

在jetpack compose中翻译动画的替代方案是OFFSET animation是的,我能够通过偏移动画实现这一点。我正在分享下面的代码和详细的评论,这样读者会更容易理解它

// Courtine Scope to Run the animation in thread
val coroutineScope = rememberCoroutineScope()
val offsetX = remember { Animatable(0f) }
val offsetY = remember { Animatable(0f) }
Image(
painter = rememberDrawablePainter(
ContextCompat.getDrawable(
context,
R.drawable.image
)
),
contentDescription = "s", contentScale = ContentScale.Crop,
modifier = Modifier
.offset {
IntOffset(
offsetX.value.toInt(),
offsetY.value.toInt()
)
}
.width(300.dp)
.height(300.dp)
)
//Finally run the animation on the Click of your button or whenever you wants 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))}
}

使用偏移也是我的解决方案。但是使用了animateDpAsState。在x轴上移动一个选项卡指示器:

val offsetState = animateDpAsState(targetValue = targetPositionDp)
Box(modifier = Modifier
.offset(offsetState.value, 0.dp)
.background(color = Color.Red)
.size(tabWidth, tabHeight))

如果您的目标是显示/隐藏一些可与翻译动画组合的内容,最好的方法是使用AnimatedVisibility:

AnimatedVisibility(
visible = isVisible,
enter = slideInVertically { it },
exit = slideOutVertically { it }
) {
SomeComposable()
}

此外,关于如何在Jetpack Compose中选择合适的动画,有一个很好的方案:https://developer.android.com/jetpack/compose/animation

只是参与讨论。正如其他人所说,使用offset修饰符是将某些转换应用于元素的最快方法。

然而,offset修饰符只影响正在显示的内容,而不影响元素的实际大小测量。如果要偏移另一个元素B所基于的元素A,则无论.offset应用于元素A,元素B的位置都将保持不变。这通常意味着你会留下一些空位。为了解决这个问题,可以使用.graphicsLayer { translationY = translationYPx }修饰符应用实际的翻译

总之,尽可能使用.offset修饰符,因为它的效率高得多,并且只有当您需要元素的大小也在屏幕外更改时才使用.graphicsLayer

最新更新