4

I'm using this library: https://github.com/software-mansion/react-native-gesture-handler

I'm a bit confused of how to get the actual x,y co-ordinates of an element. I'm explaining...

This is the initial state:

enter image description here

enter image description here

After dragging, with event.nativeEvent.absoluteX I'm getting 38

But I want 0 since the element got the left area.

I'm getting 0 only when I move my touch to the most left area. Like this,

enter image description here

But in this case, it's not working for me with this type of solution

Here is my code:

import React, {Component} from 'react';
import {Animated, View} from 'react-native';

import {PanGestureHandler, State} from 'react-native-gesture-handler';

export default class App extends Component {
  constructor(props) {
    super(props);
    this._translateX = new Animated.Value(0);
    this._translateY = new Animated.Value(0);
    this._lastOffset = {x: 0, y: 0};
    this._onGestureEvent = Animated.event(
      [
        {
          nativeEvent: {
            translationX: this._translateX,
            translationY: this._translateY,
          },
        },
      ],
      {useNativeDriver: true},
    );
  }

  _onHandlerStateChange = event => {
    if (event.nativeEvent.oldState === State.ACTIVE) {
      this._lastOffset.x += event.nativeEvent.translationX;
      this._lastOffset.y += event.nativeEvent.translationY;
      this._translateX.setOffset(this._lastOffset.x);
      this._translateX.setValue(0);
      this._translateY.setOffset(this._lastOffset.y);
      this._translateY.setValue(0);

      console.log(event.nativeEvent.absoluteX);
      console.log(event.nativeEvent.absoluteY);
    }
  };

  render() {
    return (
      <PanGestureHandler
        {...this.props}
        onGestureEvent={this._onGestureEvent}
        onHandlerStateChange={this._onHandlerStateChange}>
        <Animated.View
          style={{
            transform: [
              {translateX: this._translateX},
              {translateY: this._translateY},
            ],
          }}>
          <View style={{backgroundColor: 'green', height: 100, width: 100}} />
        </Animated.View>
      </PanGestureHandler>
    );
  }
}

Please help! Thanks in advance.

Encrypted
  • 628
  • 1
  • 10
  • 22

0 Answers0