React Native: Constraining Animated.Value
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'
})
https://facebook.github.io/react-native/docs/animations.html#interpolation
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.
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]
})
const constrainedX = this.state.pan.x.interpolate({
inputRange: [leftLimit, 0, rightLimit],
outputRange: [leftLimit, 0, rightLimit],
extrapolate: 'clamp'
})
extapolate: 'clamp' will keep it in bounds.