Limiting draggable button to the width & height of the screen (pan gesture)

33 Views Asked by At

I'm trying to make a draggable button using react-native-reanimated and react-native-gesture-handler. It can be dragged on X & Y axes. This is the code. However, the problem is that the user can drag it beyond the limit of the screen.

How do I limit how much the user can drag the button to the height & width of the screen?

const DraggableButton = (props: Props) => {


  const translateY = useSharedValue(0);
  const translateX = useSharedValue(0);
  const context = useSharedValue({ y: 0, x: 0 })

  const rStyle = useAnimatedStyle(() => {
   
    return {
      transform: [{ translateY: translateY.value }, {translateX: translateX.value}],
    };
  });

  const gesture = Gesture.Pan()
  .onStart(() => {
    context.value = { y: translateY.value, x: translateX.value } 
  })
  .onUpdate((event) => {
    translateY.value = event.translationY + context.value.y; 
    translateX.value = event.translationX + context.value.x;   
  })
  .onEnd(() => {
    
  })


  return (

    <GestureDetector gesture={gesture}>
    
    <Animated.View style={[{
      position: 'absolute',
      bottom: 30,
      right: 20,
      width: 120,
      height: 50,
      borderRadius: 100,
      backgroundColor: COLORS.ligthBlue,
      flexDirection: "row",
      alignItems: "center",
      justifyContent: "center"
    }, rStyle]}>

      <TouchableOpacity style={{flex: 1, alignItems: "center", justifyContent: "center"}}>
        <MyIcon/>
      </TouchableOpacity>
     
    </Animated.View>

    </GestureDetector>
  )
}

export default DraggableButton
0

There are 0 best solutions below