限制React Native中的Pan响应器移动

时间:2018-06-18 00:09:20

标签: react-native react-native-android

您好我正在创建一个React Native App并在其中使用PanResponder。一切正常,但我想限制元素的运动始终保持在屏幕内。目前,如果我们水平或垂直滑动,它会移出屏幕。

这是我的代码

class CourseEditScreen extends Component{

constructor(props) {
super(props);

this.state = {
  gestureState: {},
  thumbSize: width + 20,
  thumbHeight: height,
  left: width / 2,
  top: height / 2
}
}

componentWillMount() {
console.log('componentWillMount...');
this.gestureResponder = createResponder({
  onStartShouldSetResponder: (evt, gestureState) => true,
  onStartShouldSetResponderCapture: (evt, gestureState) => true,
  onMoveShouldSetResponder: (evt, gestureState) => true,
  onMoveShouldSetResponderCapture: (evt, gestureState) => true,

  onResponderGrant: (evt, gestureState) => {
  },
  onResponderMove: (evt, gestureState) => {

    let thumbSize = this.state.thumbSize;
    let thumbHeight = this.state.thumbHeight;
    if (gestureState.pinch && gestureState.previousPinch) {
      thumbSize *= (gestureState.pinch / gestureState.previousPinch);
      thumbHeight *= (gestureState.pinch / gestureState.previousPinch);
    }

    let {left, top} = this.state;

    left += (gestureState.moveX - gestureState.previousMoveX);
    top += (gestureState.moveY - gestureState.previousMoveY);

    this.setState({
      gestureState: {
        ...gestureState
      },
      left, top, thumbSize, thumbHeight
    })
  },
  onResponderTerminationRequest: (evt, gestureState) => true,
  onResponderRelease: (evt, gestureState) => {
    this.setState({
      gestureState: {
        ...gestureState
      }
    })
  },
  onResponderTerminate: (evt, gestureState) => {
  },
  onResponderSingleTapConfirmed: (evt, gestureState) => {
    console.log('onResponderSingleTapConfirmed...' + JSON.stringify(gestureState));
  },
  debug: true
});
}
render() {
  const thumbSize = this.state.thumbSize;
  const thumbHeight = this.state.thumbHeight;
  return(
    <View style={{flex: 1,}} {...this.gestureResponder}>
       <Image
      style={{ flex:1, position: 'absolute', width: thumbSize, height: thumbHeight, left: this.state.left - thumbSize/2, top: this.state.top - thumbHeight/2,}}
      source={{ uri: this.props.navigation.state.params.PhotoURL }}
      resizeMode="cover"
      pointerEvents='none'
      />
    </View>
  )
  }
  }

PS:我是React Native的新手,我在演示中使用了这段代码。这里的所有内容都按预期工作,但我希望在滚动时图像不会出现在屏幕之外。

0 个答案:

没有答案
相关问题