需要实现组件跟随手指移动,并且不能移出屏幕,具体代码如下:
import React from 'react';
import { Image, Animated } from 'react-native';
import { PanGestureHandler, State, } from 'react-native-gesture-handler';
import ScreenUtils from '../../utils/ScreenUtils';
export class MoveView extends React.Component {
whatsAppLayout = {};
constructor(props) {
super(props);
this.translateX = new Animated.Value(0);
this.translateY = new Animated.Value(0);
this._lastOffset = { x: 0, y: 0 };
this.handleGesture = Animated.event([{
nativeEvent: {
translationX: this.translateX,
translationY: this.translateY,
}
}], { useNativeDriver: true });
this._onGestureStateChange = (event) => {
if (event.nativeEvent.oldState === State.ACTIVE) {
console.log("==== _onGestureStateChange =====", event.nativeEvent)
this._lastOffset.x += event.nativeEvent.translationX;
this._lastOffset.y += event.nativeEvent.translationY;
console.log("===== _lastOffset ===", this._lastOffset);
if ((this._lastOffset.x + this.whatsAppLayout.x) <= 0) {//水平向左滑动
this._lastOffset.x = -(ScreenUtils.width - this.whatsAppLayout.width);
} else if (this._lastOffset.x > 0) {//水平向后滑动
this._lastOffset.x = 0;
}
if (this._lastOffset.y + this.whatsAppLayout.y - 44 - ScreenUtils.statusBarHeight <= 0) {//竖直向上滑动
this._lastOffset.y = -(this.whatsAppLayout.y - 44 - ScreenUtils.statusBarHeight);
} else if (this._lastOffset.y > (ScreenUtils.height - this.whatsAppLayout.y - this.whatsAppLayout.height)) {//竖直向下滑动
this._lastOffset.y = ScreenUtils.height - this.whatsAppLayout.y - this.whatsAppLayout.height;
}
this.translateX.setOffset(this._lastOffset.x);
this.translateX.setValue(0);
this.translateY.setOffset(this._lastOffset.y);
this.translateY.setValue(0);
}
}
}
render() {
return <PanGestureHandler onGestureEvent={this.handleGesture}
onHandlerStateChange={this._onGestureStateChange}
shouldCancelWhenOutside={true}>
<Animated.View ref={(view) => this.whatsAppViewRef = view}
style={{
position: 'absolute',
right: 0,
bottom: ScreenUtils.height / 5 - 16,
paddingTop: 15,
transform:
[{ translateX: this.translateX },
{ translateY: this.translateY }],
}}
onLayout={({ nativeEvent }) => {
this.whatsAppLayout = nativeEvent.layout;
}}>
<Image source={require("@assets/activity/float_group.png")}
imageStyle={{ width: 78, height: 78 }} />
</Animated.View>
</PanGestureHandler>
}
}
用的是react-native-gesture-handler库,_lastOffset是累计的偏移量。
手机屏幕的左上角的坐标是(0,0),所以:
_lastOffset.x 负数的话,说明是向左滑动,正数是向右滑动;
_lastOffset.y负数的话,说明是向上滑动,正数是向下滑动;