3

我想在此代码实验室中使用 Compose 而不是 ConstraintLayout:https ://codelabs.developers.google.com/codelabs/advanced-android-kotlin-training-property-animation/#1

如何将任何动画应用到 Compose?

4

2 回答 2

1

从 beta08 开始,现在更容易了

@Composable
fun RotateLoader() {
    val animation = rememberInfiniteTransition()
    val angle = animation.animateFloat(
        initialValue = 0f,
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            animation = tween(
                durationMillis = 1000,
                easing = LinearEasing
            ),
            repeatMode = RepeatMode.Restart
        )
    )
    Icon(
        painter = painterResource(id = R.drawable.ic_loader),
        contentDescription = null,
        modifier = Modifier.rotate(angle.value)
    )
}
于 2021-06-16T12:00:50.013 回答
1

以下是如何应用动画的指南:

以及该教程中的一段代码:

      private val rotation = FloatPropKey()
      
      private fun createDefinition(duration: Int) = transitionDefinition {
          state(0) { this[rotation] = 0f }
          state(1) { this[rotation] = 360f }
      
          transition {
              rotation using repeatable {
                  animation = tween {
                      easing = LinearEasing
                      this.duration = duration
                  }
                  iterations = Infinite
              }
          }
      }
      
      @Composable
      fun RotateIndefinitely(durationPerRotation: Int, children: @Composable() () -> Unit) {
          Transition(definition = createDefinition(durationPerRotation), initState = 0, toState = 1) {
              Rotate(it[rotation], children)
          }
      }
      
      @Composable
      fun Rotate(degree: Float, children: @Composable() () -> Unit) {
          Draw(children = children) { canvas, parent ->
              val halfWidth = parent.width.value / 2
              val halfHeight = parent.height.value / 2
      
              canvas.save()
              canvas.translate(halfWidth, halfHeight)
              canvas.rotate(degree)
              canvas.translate(-halfWidth, -halfHeight)
              drawChildren()
              canvas.restore()
          }
      }


            @Composable
        private fun RotatingPokeBall() {
            RotateIndefinitely(durationPerRotation = 4000) {
                Opacity(opacity = 0.75f) {
                    DrawImage(
                        image = +imageResource(R.drawable.pokeball),
                        tint = +colorResource(R.color.poke_red)
                    )
                }
            }
        }
于 2020-02-03T03:58:04.133 回答