[英]detect when another view is touched - dragging with PanResponder in react native
我有一個紙牌游戲,用戶可以在屏幕上拖動卡片。
如何檢測卡是否已拖過其他View組件? 我的可拖動卡片代碼是這樣的:
// A draggable card
// drag drop code example used: https://github.com/brentvatne/react-native-animated-demo-tinder
// panresponder docs: https://facebook.github.io/react-native/docs/panresponder.html
class Card extends React.Component {
componentWillMount() {
this.state = {
pan: new Animated.ValueXY(),
enter: new Animated.Value(1),
}
this._panResponder = PanResponder.create({
onMoveShouldSetResponderCapture: () => true,
onMoveShouldSetPanResponderCapture: () => true,
onPanResponderGrant: (e, gestureState) => {
Animated.spring(this.state.enter, {
toValue: .75,
}).start()
this.state.pan.setOffset({x: this.state.pan.x._value,
y: this.state.pan.y._value});
this.state.pan.setValue({x: 0, y: 0});
},
onPanResponderMove: Animated.event([
null, {dx: this.state.pan.x, dy: this.state.pan.y},
]),
onPanResponderRelease: (e, {vx, vy}) => {
// do stuff when card released
}
Animated.spring(this.state.enter, {
toValue: 1,
}).start()
this.state.pan.flattenOffset();
var velocity;
if (vx >= 0) {
velocity = clamp(vx, 3, 5);
} else if (vx < 0) {
velocity = clamp(vx * -1, 3, 5) * -1;
}
Animated.spring(this.state.pan, {
toValue: {x: 0, y: toValue},
friction: 4
}).start()
}
})
}
我不知道這是不是最好的方法,但我會得到目標視圖的onLayout
來獲得x,y,width和height ......
<View onLayout={({nativeEvent: {layout: {x,y,width,height}}) => { })} />
容器覆蓋的坐標只是(x,x +寬度)和(y,y +高度)
onPanResponderGrant
獲取可拖動的位置:
onPanResponderGrant: (e) => {
this.originX = e.pageX - e.locationX;
this.originY = e.pageY - e.locationY;
}
onPanResponderMove
你可以做這樣的事情:
onPanResponderMove: (e, gestureState) => {
const currentX0 = this.originX + gestureState.dx
const currentY0 = this.originY + gestureState.dy
}
draggable現在涵蓋從currentX0
到currentX0 + width
以及從currentY0
到currentY0 + height
......
您可以使用這些值來檢查它是否與目標視圖(x, x+width)
和(y, y+height)
重疊
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.