flattenOffset
和setOffset
方法一样,flattenOffset
方法也是Aniamted.Value
和Aniamted.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} />