GollyJer
GollyJer

Reputation: 26672

How to trigger a speed up (decrease the duration) of an Animated.timing in React Native?

I have a 3 second opacity reveal over a loading image. The animation starts with onLoadStart. onLoadEnd I'd like to quickly finish the animation regardless of the duration remaining.

i.e. - If there's 2 seconds left in the animation and the image loads I'd like finish the animation in 200ms. How?

Here's the code so far. Thanks.

import React from 'react';
import { Animated, ImageBackground } from 'react-native';

const ProgressiveImage = ({ source }) => {
  const opacity = new Animated.Value(0);

  const startOpacityAnimation = () =>
    Animated.timing(opacity, {
      toValue: 1,
      duration: 3000,
    }).start();

  const endOpacityAnimation = () => {
    // Take the current opacity value and
    // finish the animation in 200ms.
  };

  const animatedOpacity = {
    backgroundColor: opacity.interpolate({
      inputRange: [0, 1],
      outputRange: ['rgba(255, 255, 255, 0.4)', 'rgba(255, 255, 255, 0)'],
    }),
  };

  return (
    <ImageBackground
      style={{ height: 100, width: 100 }}
      source={source}
      onLoadStart={startOpacityAnimation}
      onLoadEnd={endOpacityAnimation}
    >
      <Animated.View style={{ flex: 1, ...animatedOpacity }} />
    </ImageBackground>
  );
}

Upvotes: 0

Views: 2210

Answers (1)

You can try with:

const endOpacityAnimation = () => {

    opacity.stopAnimation()

    Animated.timing(opacity, {
        toValue: 1,
        duration: 200
    }).start()

};

Or, if you want the current value of opacity in the stop animation:

opacity.stopAnimation((value) => {
  if (value < 'some number which means only 1 seconds have passed') {
    Animated.timing(opacity, {
      toValue: 1,
      duration: 200,
    }).start();
  } else {
    // something if have less than 2 seconds to end the animation
  }
});

Upvotes: 1

Related Questions