DEV Community

Sam
Sam

Posted on

Getting tap location in NativeScript

Until now, if you wanted to get the x/y touch coordinates from a tap event you needed to drop down into the underlying native code.

As of v6.5.0 NativeScript exposes this functionality for you and provides a TapGestureEventData interface. You use it like this;

import { TapGestureEventData } from "@nativescript/core";

export function myTapHandler(args: TapGestureEventData): void {
  const x = args.getX(); // x coordinate in DP
  const y = args.getY(); // y coordinate in DP
  const pointers = args.getPointerCount(); // number of pointers.
  const fingers = pointers > 1 "fingers" : "finger";

  console.log(`You tapped at (${x},${y}), with ${pointers} ${fingers}`);
}

// You tapped at (67, 123), with 1 finger.
// You tapped at (321, 45), with 2 fingers.
Enter fullscreen mode Exit fullscreen mode

The TapGestureEventData is exposed for both tap and doubleTap events.

The returned coordinates are in Device Pixels (DP). To convert them to Device Independent Pixels (DIP) use;

import { layout } from "@nativescript/core";

export myTapHandler(args: TapGestureEventData): void {
  const x_dp = args.getX();
  const x_dip = layout.toDeviceIndependentPixels(x_dp);

  console.log(`Your x coordinate is (DP: ${x_dp}, DIP: ${x_dip})`);
}

// Assuming a screen scale of 3.
// Your x coordinate is (DP: 63, DIP: 21)
Enter fullscreen mode Exit fullscreen mode

There is an open issue requesting a standardisation of UI values provided by the NativeScript API. The issue requests all API properties and methods that hold or provide UI coordinates or view dimensions are in DIP. If the core team accepts the standardisation you will no longer need to do this conversion.

  • If you need to convert DIP to DP use layout.toDevicePixels(dip);

Top comments (0)