首页 > 解决方案 > 如何在 React Native 中的两个颜色动画循​​环之间平滑过渡?

问题描述

假设我在绿色和蓝色之间运行动画循环(沿着插值有更多颜色,但我开始在前三个之间循环):

this.state = {
  colorValue: new Animated.Value(0)
};
this.interpolations = {
  background: this.state.colorValue.interpolate({
    inputRange: [0, 25, 50, 75, 100],
    outputRange: ["#64e5a5", "#216a7a", "#64e5a5", "#ffb637", "#ffd338"]
  })
};
this.backgroundAnimation = Animated.loop(
  Animated.timing(this.state.colorValue, {
    toValue: 50,
    duration: 10000
  })
);
this.backgroundAnimation.start();

请注意,我沿着插值设置了额外的颜色,希望我可以停止动画循环并开始一个新的循环,在 75 和 100 之间循环,以便在两个颜色循环之间平滑过渡。当我修改此代码以获得所需的效果时,动画似乎总是从 0 开始。我尝试将动画值设置为 50,但这并没有解决任何问题。有人可以解释这样做的正确方法吗?

注意:上面的代码不包括实际切换到下一个颜色循环的尝试,因为我真的不知道如何去做。

编辑:我快接近了,但不是很接近,第二个循环不起作用:

  this.backgroundAnimation.stop();
  this.interpolations.background = this.state.colorValue.interpolate({
    inputRange: [0, 100],
    outputRange: [JSON.stringify(this.interpolations.background), "#ffd338"]
  });

  Animated.timing(this.state.colorValue, {
    toValue: 100,
    duration: 3000
  }).start(() => {
    console.log("Done");
    this.setState({
      ...this.state,
      colorValue : new Animated.Value(0) //just spit-balling, idk
    });
    this.interpolations.background = this.state.colorValue.interpolate({
      inputRange: [0, 50, 100],
      outputRange: ["#ffd338", "#fff39b", "#ffd338"]
    });
    console.log(this.interpolations.background);


    this.backgroundAnimation = Animated.loop(
      Animated.timing(this.state.colorValue, {
        toValue: 100,
        duration: 3000
      })
    );
    this.backgroundAnimation.start();
  });

标签: javascriptreact-native

解决方案


弄清楚了 :)

this.backgroundAnimation.stop();
  this.setState({
    ...this.state,
    interpolations: {
      ...this.state.interpolations,
      background: this.state.colorValue.interpolate({
        inputRange: [0, 100],
        outputRange: [
          JSON.stringify(this.state.interpolations.background),
          "#ffd338"
        ]
      })
    }
  });
  Animated.timing(this.state.colorValue, {
    toValue: 100,
    duration: 2000
  }).start(() => {
    this.setState({
      ...this.state,
      interpolations: {
        ...this.state.interpolations,
        background: this.state.colorValue.interpolate({
          inputRange: [0, 50, 100],
          outputRange: ["#ffd338", "#ffffff", "#ffd338"]
        })
      }
    });
    this.backgroundAnimation = Animated.loop(
      Animated.timing(this.state.colorValue, {
        toValue: 100,
        duration: 2000
      })
    );
    this.backgroundAnimation.start();
  });
});

推荐阅读