import React, { useRef } from 'react'
import { Animated, Easing, PanResponder } from 'react-native'
import styled from 'styled-components/native'
const Conteainer = styled.View`
flex: 1;
justify-content: center;
align-items: center;
`
const Box = styled.View`
background-color: tomato;
width: 200px;
height: 200px;
`
const AnimatedBox = Animated.createAnimatedComponent(Box)
export default function App() {
const POSITION = useRef(
new Animated.ValueXY({
x: 0,
y: 0,
})
).current
const bgColor = POSITION.y.interpolate({
inputRange: [-300, 300],
outputRange: ['rgb(255,99,71)', 'rgb(71,166,255)'],
})
const rotation = POSITION.y.interpolate({
inputRange: [-300, 300],
outputRange: ['-360deg', '360deg'],
})
const opacityValue = POSITION.y.interpolate({
inputRange: [-300, 0, 300],
outputRange: [1, 0.5, 1],
})
const borderRadius = POSITION.y.interpolate({
inputRange: [-300, 300],
outputRange: [100, 0],
})
// Y_POSITION.addListener(() => {
// console.log(Y_POSITION),
// console.log(borderRadius),
// console.log(opacityValue)
// })
const panResponder = useRef(
PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderMove: (evt, { dx, dy }) => {
POSITION.setValue({
x: dx,
y: dy,
})
},
onPanResponderRelease: () => {
// POSITION.setValue({ x: 0, y: 0 })
Animated.spring(POSITION, {
toValue: {
x: 0,
y: 0,
},
bounciness: 10,
useNativeDriver: false,
}).start()
},
})
).current
return (
<Conteainer>
<AnimatedBox
{...panResponder.panHandlers}
style={{
borderRadius,
backgroundColor: bgColor,
transform: [...POSITION.getTranslateTransform()],
}}
/>
</Conteainer>
)
}
설명: 손으로 Box를 드래그하고 움직일 수 있는 애니매이션.
- import { PanResponder } from 'react-native' <
<AnimatedBox
{...panResponder.panHandlers}
style={{
borderRadius,
backgroundColor: bgColor,
transform: [...POSITION.getTranslateTransform()],
}}
/>
<Animated 안에...
{...panResponder.panHandlers} 를 넣어주어서 <Animated panHandlers 함수를
사용할 수 있게 한다.
const panResponder = useRef(
PanResponder.create({
onStartShouldSetPanResponder: () => true,
onPanResponderMove: (evt, { dx, dy }) => {
POSITION.setValue({
x: dx,
y: dy,
})
},
onPanResponderRelease: () => {
// POSITION.setValue({ x: 0, y: 0 })
Animated.spring(POSITION, {
toValue: {
x: 0,
y: 0,
},
bounciness: 10,
useNativeDriver: false,
}).start()
},
})
).current
Check!!!!!! Important!!!
panResponder 함수를 useRef로 만든다. useRef를 사용하는 이유는 현재 position을 찾기, 기억하기 위함.
-onStartShoudSetPanResponder => 터치 감지를 시작(onMoveShoudSetPanResponder도 가능
-onPanResponderMove => 터치되는 곳의 위치를 찍어줌.
-onPanResponderRelease => 터치가 release됬을때의 움직임을 정의, x:0, y:0 으로 Animated.spring으로 돌아가게 설정함.