我正在尝试使用平移在屏幕上拖动时实时响应来获取相对于其父级的圆的x,y坐标。
根据文档(https://facebook.github.io/react-native/docs/panresponder)locationY应该为The Y position of the touch, relative to the element
,但是,这似乎是不正确的。有什么我想念的吗?
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Obstacle from './Obstacle';
import {
StyleSheet,
Text,
View,
Dimensions,
TouchableOpacity,
PanResponder,
Animated
} from 'react-native';
import { Svg } from 'expo';
const { Circle, Rect } = Svg;
const NUM_OBSTACLES = 1;
const CIRCLE_RADIUS = 40;
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
class Canvas extends Component {
constructor(props) {
super(props);
this.state = {
pan: new Animated.ValueXY(),
mousePosition: { x: 0, y: 0 }
};
}
componentWillMount() {
// Add a listener for the delta value change
this._val = { x: 0, y: 0 };
this.state.pan.addListener(value => (this._val = value));
// Initialize PanResponder with move handling
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: (evt, gestureState) => true,
onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
onMoveShouldSetPanResponder: (evt, gestureState) => true,
onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,
onPanResponderGrant: (evt, gestureState) => {
this.state.pan.setOffset(this.state.pan.__getValue());
this.state.pan.setValue({ x: 0, y: 0 });
this.locationPageOffsetX =
evt.nativeEvent.pageX - evt.nativeEvent.locationX;
this.locationPageOffsetY =
evt.nativeEvent.pageY - evt.nativeEvent.locationY;
},
onPanResponderMove: Animated.event(
[null, { dx: this.state.pan.x, dy: this.state.pan.y }],
{
listener: (evt, gestureState) => {
console.log(
`locationX : ${evt.nativeEvent.locationX} locationY : ${
evt.nativeEvent.locationY
}`
);
}
}
)
});
}
render() {
const panStyle = {
transform: this.state.pan.getTranslateTransform()
};
// );
return (
<>
<View
style={{
borderWidth: 1,
height: '80%',
width: '100%',
backgroundColor: 'lightgrey'
}}
>
<Animated.View
{...this.panResponder.panHandlers}
style={[panStyle, styles.circle]}
/>
</View>
</>
);
}
}
const styles = StyleSheet.create({
circle: {
position: 'absolute',
backgroundColor: 'skyblue',
width: CIRCLE_RADIUS * 2,
height: CIRCLE_RADIUS * 2,
borderRadius: CIRCLE_RADIUS,
zIndex: 1
}
});
export default Canvas;
无论我将球拖到哪里,我似乎都会得到相似的值,我希望这些值在球位于左上角时更接近于零:
locationX : 48 locationY : 48
locationX : 48 locationY : 47.5
locationX : 47 locationY : 48
locationX : 44 locationY : 46.5