Search code examples
react-nativeanimationexporeact-animated

Scale an image with Animated react native expo is not applying permanently


I’m trying to increase the size of an image on user press and decrease it when he presses again with animated API using the following:

const [viewState, setViewState]= useState(true);
const scaleAnim = (new Animated.Value(.9))




const scaleOut = () => {

if(viewState){
  Animated.timing(scaleAnim, {
    toValue: 2.2,
    duration: 2000,
    useNativeDriver:true,
  }).start(()=>{setViewState(false)});
}
else{
  Animated.timing(scaleAnim, {
    toValue: .9,
    duration: 700,
    useNativeDriver:true,
  }).start(setViewState(true));
}

 };

    <Animated.View style={{transform:[{scale:scaleAnim}]}} >
      <Image style={styles.image} source={require('../path..')} />
    </Animated.View>


const styles = StyleSheet.create({
  image: {
    width:70,
    resizeMode:"contain",
    height: 45,
    alignSelf: "center",
  },

But the issue is, whenever the duration is over, the size is going back to default. I want to to stay permanently and do the opposite when the user presses again(decrease size)

Any suggestions?


Solution

  • Created a Component hope this is how you wanted....

    snack: https://snack.expo.io/neEtc2ihJ

    
    export default function App() {
      const [viewState, setViewState] = React.useState(true);
      const scale = React.useRef(new Animated.Value(1)).current;
      const [init, setInit] = React.useState(true);
      React.useEffect(() => {
        if (init) {
          setInit(false);
        } else {
          if (viewState) {
            Animated.timing(scale, {
              toValue: 2,
              duration: 1000,
              useNativeDriver: true,
            }).start();
          } else {
            Animated.timing(scale, {
              toValue: 0.5,
              duration: 700,
              useNativeDriver: true,
            }).start();
          }
        }
      }, [viewState]);
    
      const scaleOut = () => {
        setViewState(!viewState);
      };
    
      return (
        <View style={styles.container}>
          <Animated.View style={{ transform: [{ scale }] }}>
            <Image
              style={styles.image}
              source={require('./assets/snack-icon.png')}
            />
          </Animated.View>
          <Button title="animate" onPress={scaleOut} />
        </View>
      );
    }