carch
carch

Reputation: 237

Restrict panResponder from going outside the phone screen

I'm having a problem with panResponder from going outside the phone screen. I get this code from https://reactnative.dev/docs/panresponder#example. Here are some photos.

enter image description here

the box is able to drag/go outside the screen, how to avoid this? I appreciate the help.

Upvotes: 0

Views: 1163

Answers (1)

Aswin C
Aswin C

Reputation: 1222

You can to make use of Animated.diffClamp or extrapolate

diffClamp logic -

const animtion = new Animated.ValueXY(0);  // you need to update this while dragging
const translateX = Animated.diffClamp(animtion.x, 0, screenWidth - boxWidth);
const translateY = Animated.diffClamp(animtion.y, 0, screenHeight - boxHeight);

return(<View style={[styles.box,{transform:[{translateX},{translateY}]}]} />)

extrapolate logic -

const animtion = new Animated.ValueXY(0);  // you need to update this while dragging
const translateX = animation.x.interpolate({inputRange:[0,screenWidth - boxWidth],outputRange:[0,screenWidth - boxWidth], extrapolate: 'clamp'})
const translateY = animation.y.interpolate({inputRange:[0,screenHeight - boxHeight],outputRange:[0,screenHeight - boxHeight], extrapolate: 'clamp'})

return(<View style={[styles.box,{transform:[{translateX},{translateY}]}]} />)

Upvotes: 1

Related Questions