matthijs2704 - 1 year ago 105

Android Question

I need a way to convert X and Y coordinates to an angle. I have this code but I need this layout:

`180`

`90 270`

`360`

`private double getAngle(double xTouch, double yTouch) {`

double x = xTouch - (slideBtn.getWidth() / 2d);

double y = slideBtn.getHeight() - yTouch - (slideBtn.getHeight() / 2d);

switch (getQuadrant(x, y)) {

case 1:

return Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;

case 2:

return 180 - Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;

case 3:

return 180 + (-1 * Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI);

case 4:

return 360 + Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;

default:

return 0;

}

}

/**

* @return The selected quadrant.

*/

private static int getQuadrant(double x, double y) {

if (x >= 0) {

return y >= 0 ? 1 : 4;

} else {

return y >= 0 ? 2 : 3;

}

}

Edit, to clarify the problem: The problem I had was that I was getting the wrong angles for the x,y angles. For instance: 0/360 degrees is the top side of the circle and 180 degrees is the bottom side of the circle. I tried to fix it using the code above (with different quadrants, but that didn't work). The accepted answer did the trick for me.

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

I'm not really sure what are you trying to achieve, but isn't it easier to just use the atan2 function to get an angle?

http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#atan2(double, double)

If you are not familiar with the function you can read here:

http://en.wikipedia.org/wiki/Atan2

Edit, code example:

So, here is some code I think that is useful, after the discussion

```
public static double getAngle(int x, int y)
{
return 1.5 * Math.PI - Math.atan2(y,x); //note the atan2 call, the order of paramers is y then x
}
```

Basically, it calculates an angle between the negative Y-axis with the positive clockwise direction. I hope that is what you have been looking for.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**