import React, {useRef} from 'react';
import {
Animated,
Text,
View,
StyleSheet,
Button,
SafeAreaView,
} from 'react-native';
const App = () => {
// fadeAnim will be used as the value for opacity. Initial Value: 0
const fadeAnim = useRef(new Animated.Value(0)).current;
const fadeIn = () => {
// Will change fadeAnim value to 1 in 5 seconds
Animated.timing(fadeAnim, {
toValue: 1,
duration: 5000,
useNativeDriver: true,
}).start();
};
const fadeOut = () => {
// Will change fadeAnim value to 0 in 3 seconds
Animated.timing(fadeAnim, {
toValue: 0,
duration: 3000,
useNativeDriver: true,
}).start();
};
return (
<SafeAreaView style={styles.container}>
<Animated.View
style={[
styles.fadingContainer,
{
// Bind opacity to animated value
opacity: fadeAnim,
},
]}>
<Text style={styles.fadingText}>Fading View!</Text>
</Animated.View>
<View style={styles.buttonRow}>
<Button title="Fade In View" onPress={fadeIn} />
<Button title="Fade Out View" onPress={fadeOut} />
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
fadingContainer: {
padding: 20,
backgroundColor: 'powderblue',
},
fadingText: {
fontSize: 28,
},
buttonRow: {
flexBasis: 100,
justifyContent: 'space-evenly',
marginVertical: 16,
},
});
export default App;
Animated
와 쓸 수 있는 2가지 값은 2종류가 있다.Animated.Value()
: 단일 값Animated.ValueXY()
: 벡터Animated
는 3가지의 애니메이션 타입을 정의한다.Animated.decay()
: 초기 속도로 시작해서 점차 느려지다가 멈춘다.Animated.spring()
Animated.timing()
: easing function
를 사용해서 animated value
를 조절한다.Animatable Components
animated
할 수 있다.createAnimatedComponent()
는 컴포넌트를 Animatable하게 만드는데 쓰일 수 있다.const AnimationRef = useRef(new Animated.Value(0)).current;
interpolate
: value가 가지고 있는 값을 기준으로 새로운 값을 생성const widthAnimation = AnimationRef.interpolate({
inputRange : [0,10],
outputRange : ['0%', '100%']
});
// Animated 연결
<Animated.View style={{width : widthAnimation}}/>
Animated.timing(AnimationRef,{
toValue : 0, // 애니메이션의 목표, AnimationRef가 이 값으로 변화한다. ( 필수)
useNativeDriver : false, // 네이티브 드라이버 사용여부
duration : 1000, // 애니메이션의 지속시간 (milli second)
delay : 0, // 애니메이션 시작을 지연시킬 시간 (milli second)
isInteraction : true, // 기본값(true), 애니메이션이 다른 애니메이션과 상호작용하는지 여부
easing : Easing.inOut(Easing.ease), // 애니메이션 가속도 함수
}).start(()=>{
// 애니메이션이 완료되었을 때 실행할 작업
});
import {View, Animated} from 'react-native';
import React, {useEffect, useRef} from 'react';
...
const refAnimation = useRef(new Animated.Value(-380)).current;
useEffect(()=>{
Animated.timing(refAnimation, {
toValue : 0,
delay : 0,
duration : 7000,
useNativeDriver : true,
}).start(()=>{
// 애니메이션이 끝났을 때의 동작 정의
});
},
[refAnimation, navigation]);
const animatedStyle = {
height : '100%',
backgroundColor : 'skyblue',
transform : [{translateX : refAnimation}],
}
(출처 : RN 공식문서)