Last active
January 19, 2021 09:52
-
-
Save levynir/5962de39879a0b8eb1a2fd77ccedb2d8 to your computer and use it in GitHub Desktop.
React Native Rotating Component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by nirlevy on 02/07/2017. | |
* MIT Licence | |
*/ | |
import React, { Component } from 'react'; | |
import PropTypes from 'prop-types'; | |
import { Animated, Easing } from 'react-native'; | |
export class RotatingView extends Component { | |
state = { | |
spinValue: new Animated.Value(0), | |
} | |
componentDidMount() { | |
Animated.timing( | |
this.state.spinValue, // The animated value to drive | |
{ | |
toValue: this.props.toValue || 1, // Animate to 360/value | |
duration: this.props.duration || 2000, // Make it take a while | |
easing: Easing.linear, | |
useNativeDriver: true, | |
} | |
).start(this.props.onFinishedAnimating); // Starts the animation | |
} | |
render() { | |
let spin = this.state.spinValue.interpolate({ | |
inputRange: [0,1], | |
outputRange: ['0deg', '360deg'] | |
}); | |
return ( | |
<Animated.View | |
style={{ | |
...this.props.style, | |
transform: [{rotate:spin}], // Bind rotation to animated value | |
}} | |
> | |
{this.props.children} | |
</Animated.View> | |
); | |
} | |
}; | |
RotatingView.propTypes = Object.assign({},Animated.View.propTypes,{ | |
duration: PropTypes.number, //How long | |
toValue: PropTypes.number, //How much rotation, eg. 0.5 will rotate 180deg | |
onFinishedAnimating: PropTypes.func, //What to do when animation finishes, see Aminated docs | |
}); | |
/* | |
USAGE: | |
<View style={{flex: 1, flexDirection: 'row', justifyContent: 'center'}}> | |
<RotatingView | |
style={{height: 200, width: 200,}} | |
duration={3000} | |
onFinishedAnimating={( (status) => {console.log(status)} )} | |
> | |
<Image | |
style={{height:'100%', width: '100%', resizeMode: 'contain'}} | |
resizeMode='contain' | |
source={require("image.png")}/> | |
</RotatingView> | |
</View> | |
*/ |
how to rotate around a specific pivot?
@Houman7601 I'm not sure actually. sorry.
@levynir: you can rotate around different axis by modifying the 'transform' (in the render() function) to either rotateY or rotateX
render() {
let spin = this.state.spinValue.interpolate({
inputRange: [0, 1],
outputRange: ["0deg", "360deg"]
});
return (
<Animated.View
style={{
...this.props.style,
transform: [{ rotateY: spin }] // Bind rotation to animated value
}}
>
{this.props.children}
</Animated.View>
);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@benallfree that's excellent!