Created
April 3, 2020 20:24
-
-
Save kyle-ssg/697570a7d5edc0e14cc6967b2e40b7ba to your computer and use it in GitHub Desktop.
Animation example
This file contains 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
import React, {PureComponent} from 'react'; | |
import {Animated, View, StyleSheet, Text, Easing} from 'react-native'; | |
export default class App extends PureComponent { | |
static displayName = 'TheComponent'; | |
animatedValue = new Animated.Value(0); | |
render() { | |
// Coordinates of the parent View | |
const width = 50; | |
const height = 50; | |
const top = 250; | |
const left = 100; | |
// The start and end scale of the animation | |
const startScale = 1; | |
const finalScale = 4; | |
// The coordinates of the child component | |
const innerTop = -top; | |
const innerLeft = -left; | |
const innerWidth = 100; | |
const innerHeight = 100; | |
// Helper functions to position child relative to parent | |
const scaleInner = (scale) => (scale ? 1 / scale : 0); | |
const translateInnerY = (scale) => | |
top * (scale - 1) - (height / 2) * (scale - 1); | |
const translateInnerX = (scale) => | |
left * (scale - 1) - (width / 2) * (scale - 1); | |
// Animation interpolation | |
const scale = this.animatedValue.interpolate({ | |
inputRange: [0, 1], | |
outputRange: [startScale, finalScale], | |
}); | |
const scaleInPlace = this.animatedValue.interpolate({ | |
inputRange: [0, 1], | |
outputRange: [scaleInner(startScale), scaleInner(finalScale)], | |
}); | |
const translateX = this.animatedValue.interpolate({ | |
inputRange: [0, 1], | |
outputRange: [translateInnerX(startScale), translateInnerX(finalScale)], | |
}); | |
const translateY = this.animatedValue.interpolate({ | |
inputRange: [0, 1], | |
outputRange: [translateInnerY(startScale), translateInnerY(finalScale)], | |
}); | |
return ( | |
<View style={{flex: 1, margin: 50}}> | |
<Animated.View | |
style={[ | |
{ | |
transform: [{scale}], | |
top: top, | |
left: left, | |
width, | |
height, | |
}, | |
styles.parent, | |
]}> | |
<Text>Parent</Text> | |
<Animated.View | |
style={[ | |
{ | |
transform: [{scale: scaleInPlace}, {translateX}, {translateY}], | |
top: innerTop, | |
left: innerLeft, | |
width: innerWidth, | |
height: innerHeight, | |
}, | |
styles.child, | |
]}> | |
<Text>Child</Text> | |
</Animated.View> | |
</Animated.View> | |
</View> | |
); | |
} | |
} | |
const styles = StyleSheet.create({ | |
parent: { | |
backgroundColor: 'blue', | |
position: 'absolute', | |
overflow: 'visible', | |
justifyContent: 'center', | |
alignItems: 'center', | |
}, | |
child: { | |
position: 'absolute', | |
backgroundColor: 'red', | |
justifyContent: 'center', | |
alignItems: 'center', | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment