Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NativeScript Angular - Get X and Y on tap event

I'm doing a Nativescript-Angular-App and i have a problem.

The user has to click on the right position on a picture.

I don't understand how to get the coordinates of a simple tap.

I can get the coordinate with the touch gesture (TouchGestureEventData) but it provides a stream of informations. I just want one data.

  • GestureEventData hasn't GetX() method.
  • TouchGestureEventData has GetX() method but I want only the first touch.

I have tried with touch:

public onTouch(args: TouchGestureEventData) {
     console.log(args.getActivePointers()[0].getX());
}

But i get too many data (every movement).

Is there a way to get the coordinate just with a simple tap?

Thanks!

like image 384
Wandrille Avatar asked Jan 29 '23 21:01

Wandrille


2 Answers

If you just want to get a single touch event. what you can do is check if event action is a down action or alternatively up action. for example the below code will just get you the X and Y coordinates of the touch-down event and will only happen once for each touch event.

public onTouch(e: TouchGestureEventData) {
    if (e && e.action === 'down') {
        this.xCoord = e.getX();
        this.yCoord = e.getY();
    }
}
like image 147
JoshSommer Avatar answered Feb 05 '23 18:02

JoshSommer


Been researching this issue, and found a way for the tap event in iOS:

onTap(e) {
    const loc = e.ios.locationInView(e.object.ios);
    console.log("(x,y) in dp: " + loc.x + "," + loc.y);
}  

I found that e.ios is the native object representation of that tap event, and tried to see what I can do with it, so I used Chrome DevTools, and started typing e.ios.location, and got the locationInView() autocomplete. I then searched for it in Apple's documentation and found that the function gets a UIView as an argument. So I tried e.ios.locationInView(e.object); and got an exception, so I remembered UIView is the iOS representation of nativescript's View class, so I tried e.ios.locationInView(e.object.ios); and got the CGPoint representing the tap coordinates in the view.
It is important to note that loc.x and loc.y are in dp units.

For Android it's a lot simpler:

onTap(e) {
    const x = e.android.getX();
    const y = e.android.getY();
    console.log("(x,y) in pixels: " + x + "," + y);
}  

Important to note that in this case the coordinates are in pixel units, so in order to convert it to dp, you would first have to import { screen } from "platform"; where your imports are, and then in order to get the x coordinate in dp, you would:
e.android.getX() / screen.mainScreen.scale

like image 43
bks Avatar answered Feb 05 '23 18:02

bks