Mobile App/React native

[React-Native] Animation - 3 / interpolate, loop, sequence

bugtype 2020. 1. 25. 13:50

 

 

 

 

import React, {Component} from 'react';

import ReactNative from 'react-native';



const {View, StyleSheet, Dimensions, Animated} = ReactNative;



const SQUARE_H = 100;

const SQUARE_W = 100;

const WINDOW_H = Dimensions.get('window').height;

const WINDOW_W = Dimensions.get('window').width;



export default class MovingSquareOriginal extends Component {

constructor(props, context) {

super(props, context);

this.state = {

value: new Animated.Value(0),

};

}



componentWillMount() {

this.translateX = this.state.value.interpolate({

inputRange: [0, 0.5, 1],

outputRange: [0, WINDOW_W / 2 - SQUARE_W, 0],

});



this.translateY = this.state.value.interpolate({

inputRange: [0, 1],

outputRange: [0, WINDOW_H - SQUARE_W * 2],

extrapolate: 'clamp',

});



this.rotate = this.state.value.interpolate({

inputRange: [0, 1],

outputRange: ['0deg', '90deg'],

});



this.opacity = this.state.value.interpolate({

inputRange: [0, 1],

outputRange: [0, 1],

});



this.color = this.state.value.interpolate({

inputRange: [0, 1],

outputRange: ['#fff', '#000'],

});

}



componentDidMount() {

Animated.loop(

Animated.sequence([

Animated.timing(this.state.value, {

duration: 1000,

toValue: 1,

delay: 500,

}),

Animated.timing(this.state.value, {

duration: 1000,

toValue: 0,

delay: 500,

}),

]),

).start();

}



getTransform() {

return {

transform: [

{translateX: this.translateX},

{translateY: this.translateY},

{rotate: this.rotate},

],

opacity: this.opacity,

backgroundColor: this.color,

};

}



render() {

return <Animated.View style={[s.square, this.getTransform()]} />;

}

}



const s = StyleSheet.create({

square: {

height: SQUARE_H,

width: SQUARE_W,

backgroundColor: '#ff0000',

},

});

 

 

 

interpolate - 0부터 1을 입력하면 내부적으로 duration과 함께 계산한다. 

예 ) inputRange 0,1  duration 1초 일 경우, RN은 frame에 60이니... 1초를 60으로 나누면 1 frame이 약 0.016초 라고 생각하면 된다.

매 frame마다 0.016 더하는 거다

0 frame - 0

1 frame - 0.016

2 frame - 0.032

3 frame - 0.048

...

...

60 frame - 1

 

loop - 애니메이션을 반복 시키고 싶을 때 사용한다.

sequence 애니메이션을 순서적으로 보여주고 싶을 때 사용한다.

 

* useNativeDriver를 안사용하는 이유는 tranform이 아니면, native에서 코드가 작동하지 않기에 사용하지 못한다. 사용하고 싶으면 분리해야한다.

- 예) opacity, backgroundColor