-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathDragAndSnapExample.tsx
81 lines (77 loc) · 1.87 KB
/
DragAndSnapExample.tsx
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import React from 'react';
import { View } from 'react-native';
import Animated, {
useSharedValue,
withSpring,
useAnimatedStyle,
useAnimatedGestureHandler,
interpolate,
Extrapolate,
} from 'react-native-reanimated';
import {
PanGestureHandler,
PanGestureHandlerGestureEvent,
} from 'react-native-gesture-handler';
function DragAndSnap(): React.ReactElement {
const translation = {
x: useSharedValue(0),
y: useSharedValue(0),
};
type AnimatedGHContext = {
startX: number;
startY: number;
};
const gestureHandler = useAnimatedGestureHandler<
PanGestureHandlerGestureEvent,
AnimatedGHContext
>({
onStart: (_, ctx) => {
ctx.startX = translation.x.value;
ctx.startY = translation.y.value;
},
onActive: (event, ctx) => {
translation.x.value = ctx.startX + event.translationX;
translation.y.value = ctx.startY + event.translationY;
},
onEnd: (_) => {
translation.x.value = withSpring(0);
translation.y.value = withSpring(0);
},
});
const stylez = useAnimatedStyle(() => {
const H = Math.round(
interpolate(translation.x.value, [0, 300], [0, 360], Extrapolate.CLAMP)
);
const S = Math.round(
interpolate(translation.y.value, [0, 500], [100, 50], Extrapolate.CLAMP)
);
const backgroundColor = `hsl(${H},${S}%,50%)`;
return {
transform: [
{
translateX: translation.x.value,
},
{
translateY: translation.y.value,
},
],
backgroundColor,
};
});
return (
<View style={{ flex: 1, margin: 50 }}>
<PanGestureHandler onGestureEvent={gestureHandler}>
<Animated.View
style={[
{
width: 40,
height: 40,
},
stylez,
]}
/>
</PanGestureHandler>
</View>
);
}
export default DragAndSnap;