I'm making a React-Native app and the scenario is this:
I want the user to be able to pan a view, but not wholly the way he wants.
I'd like to constraint how much the view can move when being dragged by the user.
I've read through the documentation of both the PanResponder
and Animated
API (multiple times), but can't find anything that does this, neither can I find anyone else that implemented something alike.
Constraining in the panresponder's event?
onPanResponderMove: Animated.event([null,{
dx: this.state.pan.x, //Some function here to constrain the value?
dy: this.state.pan.y
}]),
Constraining while applying the transforms?
style = {
transform: {
transformX: ...,//Use interpolate to constrain the values somehow?
transformY: ...
}
}
Or you could use the extrapolate
, extrapolateRight
or extrapolateLeft
properties:
const maxX = 200;
const constrainedX = this.state.pan.x.interpolate({
inputRange: [0, maxX],
outputRange: [0, maxX],
extrapolateRight: 'clamp'
})
seems to me to do the same as @mieszko4, of which I don't know why the Infinity
hack was needed.
https://facebook.github.io/react-native/docs/animations.html#interpolation
The solution provided by @stinodes will degrade performance. Why not using interpolate
in the following way:
const maxX = 200;
const constrainedX = this.state.pan.x.interpolate({
inputRange: [0, maxX, Infinity],
outputRange: [0, maxX, maxX]
})
The solution I came up with:
Since Animated.event()
returns a function, you can just pass your processed gestureState, with constrained values, into that function.
It'd look something like this:
onPanResponderMove: (evt, gestureState) => {
let newdx = gestureState.dx, //DO SOMETHING WITH YOUR VALUES
newdy = gestureState.dy;
Animated.event([null,{
dx: this.state.pan.x,
dy: this.state.pan.y
}])(evt, {dx: newdx, dy: newdy});
},
Whether it's it should be done is debatable though.
const constrainedX = this.state.pan.x.interpolate({
inputRange: [leftLimit, 0, rightLimit],
outputRange: [leftLimit, 0, rightLimit],
extrapolate: 'clamp'
})
extapolate: 'clamp' will keep it in bounds.