Categories
JavaScript Answers React Native Answers

How to animate the rotation of an Image with React Native?

Spread the love

Sometimes, we want to animate the rotation of an Image with React Native.

In this article, we’ll look at how to animate the rotation of an Image with React Native.

How to animate the rotation of an Image with React Native?

To animate the rotation of an Image with React Native, we can use the animated value’s interpolate method.

For instance, we write:

import * as React from 'react';
import { View, Animated, Text, Easing } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

const spinValue = new Animated.Value(0);

export default function App() {
  React.useEffect(() => {
    Animated.timing(spinValue, {
      toValue: 1,
      duration: 3000,
      easing: Easing.linear,
      useNativeDriver: true,
    }).start();
  }, []);

  const spin = spinValue.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '360deg'],
  });

  return (
    <Animated.Image
      style={{ transform: [{ rotate: spin }], width: 200, height: 300 }}
      source={{ uri: 'https://picsum.photos/200/300' }}
    />
  );
}

to add the Animated.Image component to add an image that can animate.

Then we define the spinValue animated value with Animated.Value.

Next, we call Animated.timing with spinValue and some options for the animation.

toValue is the value of the inputValue to animate to.

duration is the duration of the animation in milliseconds.

easing is the easing.

Next, we call spinValue.interpolate to interpolate the animation values.

We call start to start the animation in the useEffect callback.

Conclusion

To animate the rotation of an Image with React Native, we can use the animated value’s interpolate method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *