How to get distance between two points in Android?
Asked Answered
P

3

11

I set the two pointers inside ACTION_POINTER_DOWN

point1.set(event.getX(0),event.getY(0));
point2.set(event.getX(1),event.getY(1));

How can I get the distance between this two points? Is there any way to get it?

I want the distance to make some Scrolling effect. With the distance, I can use it like a scalefactor and resize my Layouts.

I hope someone can tell me how to do that!

Polyploid answered 14/10, 2015 at 10:13 Comment(1)
You could use Pythagoras theory to calculate!Indium
P
25

Its not just Android..

We remember from trigonometry class that distance between two points can be calculated using Pythagorean Theorem as demonstrated here

But in code basically what you want is as follows:

double d = Math.sqrt(Math.pow(event.getX(1) - event.getX(0), 2) + Math.pow(event.getY(1) - event.getY(0), 2));

Where d is distance between two points

Personalize answered 14/10, 2015 at 10:18 Comment(3)
I get an error... sqrt (double) cannot applied to sqrt (double,double)Polyploid
Sorry, there was a typo in the code, I was supposed to sum the two squares, but accidentally added a comma.Loveridge
A small Operator makes the difference! Thank you for your solution!!Polyploid
S
10
Math.hypot(x1 - x2, y1 - y2)

should perform a bit faster.

Math.hypot

Soleure answered 22/8, 2019 at 8:15 Comment(1)
I think your answer would be way better if you added a short explanation on why this should be a bit faster.Shearer
P
2

Finding distance between 2 points is not android specific:

    double x1 = event.getX(1);
    double y1 = event.getY(1);
    double x2 = event.getX(0);
    double y2 = event.getY(0);
    double x = Math.sqrt(Math.pow(x2 - x1, 2) - Math.pow(y2 - y1, 2));
Parette answered 14/10, 2015 at 10:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.