反应本机声像响应器的XY值不正确

时间:2019-02-19 08:30:31

标签: react-native

我正在尝试从平移响应器获取xy值,但根据屏幕上动画视图的位置,这些值似乎并不准确。

export default class Dragabble extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            pan: new Animated.ValueXY({ x: 0, y: 0 }),
            scale: new Animated.Value(1),
            x: 0,
            y: 0
        }
    }

    UNSAFE_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,
            onMoveShouldSetPanResponderCapture: () => true,
            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 }
            ]),
            onPanResponderRelease: (e, gestureState) => {

                this.props.updateSkuBoxes(this.props.image_name, this.props.id, gestureState.moveX, gestureState.moveY, this.props.width, this.props.height)
                this._animatedValue.flattenOffset();
            }
        });
    }

    handleOnPressBack = () => {
        NavigationService.pop()
    }

    hexToRGB = (hex, alpha) => {
        var r = parseInt(hex.slice(1, 3), 16),
            g = parseInt(hex.slice(3, 5), 16),
            b = parseInt(hex.slice(5, 7), 16);

        if (alpha) {
            return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";
        } else {
            return "rgb(" + r + ", " + g + ", " + b + ")";
        }
    }

    handleLayoutChange = (event) => {
        this.feedPost.measure((fx, fy, width, height, px, py) => {
            console.log('Component width is: ' + width)
            console.log('Component height is: ' + height)
            console.log('X offset to page: ' + px)
            console.log('Y offset to page: ' + py)
        })
    }

    render() {

        // Calculate the transform property and set it as a value for our style which we add below to the Animated.View component
        let viewStyle = { transform: this._animatedValue.getTranslateTransform() }

        return (
            <View>
                <Animated.View style={viewStyle}{...this._panResponder.panHandlers}>
                    <View ref={view => { this.feedPost = view; }} onLayout={(event) => { this.handleLayoutChange(event) }} style={{ height: this.props.height, width: this.props.width, backgroundColor: this.hexToRGB(this.props.color_cd, 0.4), borderWidth: 2, borderColor: this.props.color_cd, margin: 5 }}></View>
                </Animated.View>
            </View>

        )
    }
}

该视图从屏幕的左上角(0,0)开始,但是当它移动甚至平移一点时,坐标就会显示其他值。

0 个答案:

没有答案