reactjsreact-nativereact-animatedreact-animationsreact-image

React Native Background Animation Reverse


I have an application that I wrote in react native. I tried to make an animated background with Animated Api and Image for this app. Animation works but only in one direction. After the animation runs, I want it to run in the opposite direction it goes. I'm new to Animated Api, please help me! I leave the codes below.

import {
  ANIMATION_DURATION,
  ANIMATION_TO_VALUE,
  INPUT_RANGE_END,
  INPUT_RANGE_START,
  OUTPUT_RANGE_END,
  OUTPUT_RANGE_START,
} from "../constant";
import { DevHeight, DevWidth } from "../utils/device";
import React, { useEffect, useRef } from "react";
import {
  StyleSheet,
  Animated,Easing,
} from "react-native";
export const AnimatedBackground = ({backgroundImage,style}) => {

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

  const translate = () => {
    translateValue.setValue(initialValue);
    Animated.loop(
      Animated.timing(translateValue, {
        toValue: ANIMATION_TO_VALUE,
        duration: ANIMATION_DURATION,
        easing: Easing.linear,
        useNativeDriver: true,
      })
    ).start();
  };

  useEffect(() => {
    translate();
  }, [translateValue]);

  const translateAnimation = translateValue.interpolate({
    inputRange: [INPUT_RANGE_START, INPUT_RANGE_END],
    outputRange: [OUTPUT_RANGE_START, OUTPUT_RANGE_END],
  });

  return (
    <Animated.Image
      resizeMode={'repeat'}
      style={[styles.background,{
        transform: [
          {
            translateX: translateAnimation,
          },
          {
            translateY: translateAnimation,
          },
        ],
      },style]}
      source={backgroundImage} />
  );
};

export default AnimatedBackground;

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  background: {
    position: 'absolute',
    width: DevWidth*2,
    height: DevHeight*2,
    flex:1,
    top: 0,
    opacity: 0.2,
    transform: [
      {
        translateX: 0,
      },
      {
        translateY: 0,
      },
    ],
  },
});

Solution

  • const translate = () => {
      Animated.loop(
        Animated.sequence([
          Animated.timing(translateValue, {
            toValue: ANIMATION_TO_VALUE,
            duration: ANIMATION_DURATION,
            easing: Easing.linear,
            useNativeDriver: true,
          }),
          Animated.timing(translateValue, {
            toValue: initialValue,
            duration: ANIMATION_DURATION,
            easing: Easing.linear,
            useNativeDriver: true,
          }),
        ]),
      ).start();
    };
    

    Please try with above update.