|
| 1 | +import Animated, { |
| 2 | + useAnimatedStyle, |
| 3 | + useSharedValue, |
| 4 | + withSpring, |
| 5 | +} from 'react-native-reanimated'; |
| 6 | +import { |
| 7 | + Gesture, |
| 8 | + GestureDetector, |
| 9 | + enableExperimentalWebImplementation, |
| 10 | +} from 'react-native-gesture-handler'; |
| 11 | +import { StyleSheet, View } from 'react-native'; |
| 12 | + |
| 13 | +import { StatusBar } from 'expo-status-bar'; |
| 14 | + |
| 15 | +enableExperimentalWebImplementation(true); |
| 16 | + |
| 17 | +export default function App() { |
| 18 | + const isPressed = useSharedValue(false); |
| 19 | + const offset = useSharedValue({ x: 0, y: 0 }); |
| 20 | + |
| 21 | + const animatedStyle = useAnimatedStyle(() => { |
| 22 | + return { |
| 23 | + transform: [ |
| 24 | + { translateX: offset.value.x }, |
| 25 | + { translateY: offset.value.y }, |
| 26 | + { scale: withSpring(isPressed.value ? 1.2 : 1) }, |
| 27 | + ], |
| 28 | + backgroundColor: isPressed.value ? 'blue' : 'navy', |
| 29 | + cursor: isPressed.value ? 'grabbing' : 'grab', |
| 30 | + }; |
| 31 | + }); |
| 32 | + |
| 33 | + const gesture = Gesture.Pan() |
| 34 | + .manualActivation(true) |
| 35 | + .onBegin(() => { |
| 36 | + 'worklet'; |
| 37 | + isPressed.value = true; |
| 38 | + }) |
| 39 | + .onChange((e) => { |
| 40 | + 'worklet'; |
| 41 | + offset.value = { |
| 42 | + x: e.changeX + offset.value.x, |
| 43 | + y: e.changeY + offset.value.y, |
| 44 | + }; |
| 45 | + }) |
| 46 | + .onFinalize(() => { |
| 47 | + 'worklet'; |
| 48 | + isPressed.value = false; |
| 49 | + }) |
| 50 | + .onTouchesMove((_, state) => { |
| 51 | + state.activate(); |
| 52 | + }); |
| 53 | + |
| 54 | + return ( |
| 55 | + <View style={styles.container}> |
| 56 | + <StatusBar style="auto" /> |
| 57 | + <GestureDetector gesture={gesture}> |
| 58 | + <Animated.View style={[styles.ball, animatedStyle]} /> |
| 59 | + </GestureDetector> |
| 60 | + </View> |
| 61 | + ); |
| 62 | +} |
| 63 | + |
| 64 | +const styles = StyleSheet.create({ |
| 65 | + container: { |
| 66 | + flex: 1, |
| 67 | + backgroundColor: '#fff', |
| 68 | + alignItems: 'center', |
| 69 | + justifyContent: 'center', |
| 70 | + }, |
| 71 | + ball: { |
| 72 | + width: 100, |
| 73 | + height: 100, |
| 74 | + borderRadius: 100, |
| 75 | + backgroundColor: 'blue', |
| 76 | + alignSelf: 'center', |
| 77 | + }, |
| 78 | +}); |
0 commit comments