如何循环和反转React Native动画

huangapple go评论54阅读模式
英文:

How to loop and reverse react-native animation

问题

在我的 Expo 应用中,有一张图片,我想要将其用作加载动画。我想要实现的动画是无限循环地将图像放大、缩小、再放大等,就像一个“脉动”一样。我正在使用 React Native 动画。

我尝试了循环两个动画(一个正向,一个反向),但没有成功。

我做错了什么?

以下是我的代码:

const scaleValue = useRef(new Animated.Value(0)).current;

useEffect(() => {
  Animated.loop(Animated.timing(scaleValue, {
    toValue: 0,
    duration: 800,
    useNativeDriver: true
  }).start(() => {
    Animated.timing(scaleValue, {
      toValue: 1,
      duration: 800,
      useNativeDriver: true
    }).start();
  }));
}, []);

const interpolated = scaleValue.interpolate({
  inputRange: [0, 1],
  outputRange: [1, 0],
});

return (
  <Animated.Image
    style={[
      {
        width: 165,
        height: 75,
        transform: [{ scale: interpolated }],
      },
    ]}
    source={Logo}
  </Animated.Image>
);

希望这对你有所帮助。

英文:

In my expo app have an image that i want to use for a loading animation. The animation i want to achieve is an infinite loop of scaling the image bigger, smaller, bigger etc. like a "pulse". I am using react native animation.

I have tried to loop two animations ( one forward and one reverse ) without any luck.

What am i doing wrong?

Here is my code:

  const scaleValue = useRef(new Animated.Value(0)).current;

  useEffect(() =&gt; {
    Animated.loop(Animated.timing(scaleValue, {
      toValue: 0,
      duration: 800,
      useNativeDriver: true
    }).start(() =&gt; {
      Animated.timing(scaleValue, {
        toValue: 1,
        duration: 800,
      useNativeDriver: true
      })
    }))
  }, []);

  const interpolated = scaleValue.interpolate({
    inputRange: [0, 1],
    outputRange: [1, 0],
  });

      return (&lt;Animated.Image
        style={[
          {
            width: 165,
            height: 75,
            transform: [{scale: interpolated}],
          },
        ]}
        source={Logo}
      &gt;&lt;/Animated.Image&gt;)


答案1

得分: 2

你可以使用 sequence() 方法。

Animated.loop(
  Animated.sequence([
    Animated.timing(scaleValue, {
      toValue: 0,
      duration: 800,
      useNativeDriver: true,
    }),
    Animated.timing(scaleValue, {
      toValue: 1,
      duration: 800,
      useNativeDriver: true,
    }),
  ]),
);
英文:

You can use sequence() method.

Animated.loop(
  Animated.sequence([
    Animated.timing(scaleValue, {
      toValue: 0,
      duration: 800,
      useNativeDriver: true,
    }),
    Animated.timing(scaleValue, {
      toValue: 1,
      duration: 800,
      useNativeDriver: true,
    }),
  ]),
);

huangapple
  • 本文由 发表于 2023年3月4日 07:36:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定