flattenOffset

setOffset方法一样,flattenOffset方法也是Aniamted.ValueAniamted.ValueXY共有的。这个方法也是主要用于处理PanResponder,在方法onPanResponderRelease中调用。

方法flattenOffset会接受offset值,之后用这个值作为基准值(偏差值)加上Aniamted.Value的当前值作为Animated.Value的值,之后把offset值重置为0.比如,现在有offset值100,Animated.Value值为50,当我们调用flattenOffset方法的时候,offset值会被重置为0,而Animated.Value的值为150.

  componentWillMount() {
    this._animatedValue = new Animated.ValueXY()
    this._value = {x: 0, y: 0}

    this._animatedValue.addListener((value) => this._value = value);
    this._panResponder = PanResponder.create({
      onMoveShouldSetResponderCapture: () => true, //Tell iOS that we are allowing the movement
      onMoveShouldSetPanResponderCapture: () => true, // Same here, tell iOS that we allow dragging
      onPanResponderGrant: (e, gestureState) => {
        this._animatedValue.setOffset({x: this._value.x, y: this._value.y});
        this._animatedValue.setValue({x: 0, y: 0});
      },
      onPanResponderMove: Animated.event([
        null, {dx: this._animatedValue.x, dy: this._animatedValue.y}
      ]), // Creates a function to handle the movement and set offsets
      onPanResponderRelease: () => {
        this._animatedValue.flattenOffset(); // Flatten the offset so it resets the default positioning
      }
    });
  },


// To use

<Animated.View style={[styles.box, {transform: this._animatedValue.getTranslateTransform()}]} {...this._panResponder.panHandlers} />

results matching ""

    No results matching ""