首页 > 解决方案 > Jetpack Compose“最短”旋转动画

问题描述

我试图在jetpack compose中做一个指南针。但是我在制作动画时遇到了问题。我有一个@Composable可以让用户手机旋转并以相反方向旋转指南针图像。我animateFloatAsState这样使用:

val angle: Float by animateFloatAsState(
    targetValue = -rotation, \\ rotation is retrieved as argument
    animationSpec = tween(
        durationMillis = UPDATE_FREQUENCY, \\ rotation is retrieved with this frequency
        easing = LinearEasing
    )
)

Image(
    modifier = Modifier.rotate(angle),
    // rest of the code for image
)

一切看起来都很好,但是当rotation1to359或以相反的方式更改时会出现问题。动画不会2向左旋转度数,而是358向右旋转度数,这看起来很糟糕。有没有办法制作使用最短方式的旋转动画?

标签: androidkotlinanimationandroid-jetpack-compose

解决方案


我假设您已经(或可以获得)访问当前旋转值(即当前角度)的权限,并将其存储起来。

然后,

val angle: Float by animateFloatAsState(
    targetValue = if(rotation > 360 - rotation) {-(360 - rotation)} else rotation
    animationSpec = tween(
        durationMillis = UPDATE_FREQUENCY, \\ rotation is retrieved with this frequency
        easing = LinearEasing
    )
)

Image(
    modifier = Modifier.rotateBy(currentAngle, angle), //Custom Modifier
    // rest of the code for image
)

rotateBy 是一个自定义修饰符,应该不难实现。使用内置的旋转修改器来构建它。逻辑将保持不变


推荐阅读