Reputation: 1732
I am making a WPF control (knob). I am trying to figure out the math to calculate the angle (0 to 360) based on a mouse click position inside the circle.
For instance, if I click where the X,Y is on the image, I would have a point X,Y. I have the centerpoint as well, and cannot figure out how to get the angle.
My code below:
internal double GetAngleFromPoint(Point point, Point centerPoint)
{
double dy = (point.Y - centerPoint.Y);
double dx = (point.X - centerPoint.X);
double theta = Math.Atan2(dy,dx);
double angle = (theta * 180) / Math.PI;
return angle;
}
Upvotes: 10
Views: 4146
Reputation: 128061
The correct calculation is this:
var theta = Math.Atan2(dx, -dy);
var angle = ((theta * 180 / Math.PI) + 360) % 360;
You could also let Vector.AngleBetween do the calculation:
var v1 = new Vector(dx, -dy);
var v2 = new Vector(0, 1);
var angle = (Vector.AngleBetween(v1, v2) + 360) % 360;
Upvotes: 2
Reputation: 39085
You've got it almost right:
internal double GetAngleFromPoint(Point point, Point centerPoint)
{
double dy = (point.Y - centerPoint.Y);
double dx = (point.X - centerPoint.X);
double theta = Math.Atan2(dy,dx);
double angle = (90 - ((theta * 180) / Math.PI)) % 360;
return angle;
}
Upvotes: 9