Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: Constraining Animated.Value

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: ...
    }
}
like image 841
stinodes Avatar asked Apr 20 '16 14:04

stinodes


People also ask

How do I get the value of animation in React Native?

To get the current value of Animated. Value with React Native, we call addListener on the animated value object. to call spinValue. addListener with a callback to get the current value of the animated value from the value property.

How do you check if animation is finished React Native?

The updated answer should be: . start(({finished}) => { if (finished) { console. log('animation ended!) } })


2 Answers

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

like image 127
deb0ch Avatar answered Sep 24 '22 03:09

deb0ch


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.

like image 22
stinodes Avatar answered Sep 24 '22 03:09

stinodes