DEV Community

Sam
Sam

Posted on

1 3

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);
đź‘‹ While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

đź‘‹ Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay