-
Notifications
You must be signed in to change notification settings - Fork 0
/
AnimatedBox.js
65 lines (60 loc) · 1.68 KB
/
AnimatedBox.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import React from 'react';
import {View, StyleSheet, Dimensions} from 'react-native';
import Animated, {
useSharedValue,
useAnimatedGestureHandler,
useAnimatedStyle,
withSpring,
} from 'react-native-reanimated';
import {PanGestureHandler} from 'react-native-gesture-handler';
const BOX_SIZE = 200;
const {width: deviceWidth, height: deviceHeight} = Dimensions.get('screen');
const INITIAL_COORDINATES = {
X: (deviceWidth - BOX_SIZE) / 2,
Y: (deviceHeight - BOX_SIZE) / 2,
};
export const AnimatedBox = () => {
const translateX = useSharedValue(INITIAL_COORDINATES.X);
const translateY = useSharedValue(INITIAL_COORDINATES.Y);
const onGestureEvent = useAnimatedGestureHandler({
onStart: (_, ctx) => {
ctx.offsetX = translateX.value;
ctx.offsetY = translateY.value;
},
onActive: (event, ctx) => {
translateX.value = ctx.offsetX + event.translationX;
translateY.value = ctx.offsetY + event.translationY;
},
onEnd: () => {
translateX.value = withSpring(INITIAL_COORDINATES.X);
translateY.value = withSpring(INITIAL_COORDINATES.Y);
},
});
const animatedStyle = useAnimatedStyle(() => {
return {
transform: [
{translateX: translateX.value},
{translateY: translateY.value},
],
};
});
return (
<View style={styles.container}>
<PanGestureHandler onGestureEvent={onGestureEvent}>
<Animated.View style={animatedStyle}>
<View style={styles.box} />
</Animated.View>
</PanGestureHandler>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
box: {
backgroundColor: 'purple',
width: BOX_SIZE,
height: BOX_SIZE,
},
});