2013-01-19 145 views
10

我正在制作一个WPF控件(旋钮)。我试图找出计算角度(0到360)的基础上的一个鼠标点击位置的数学算法。例如,如果我点击X,Y在图像上的位置,我会得到一个点X,Y。我也有中心点,并且无法弄清楚如何获得角度。计算点击点的角度

circle image

我下面的代码:

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; 
} 

回答

8

你明白了差不多吧:

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; 
} 
+0

我的工作方式是:double angle =(360 - ((theta * 180)/ Math.PI))%360; –

+0

谢谢!我很感激。我一直在Google上搜索几个小时! –

3

你需要

double theta = Math.Atan2(dx,dy); 
+0

正确!再次感谢。 –

2

正确的计算是这样的:

var theta = Math.Atan2(dx, -dy); 
var angle = ((theta * 180/Math.PI) + 360) % 360; 

你也可以让Vector.AngleBetween做计算:

var v1 = new Vector(dx, -dy); 
var v2 = new Vector(0, 1); 
var angle = (Vector.AngleBetween(v1, v2) + 360) % 360; 
+0

从未见过Vector.AngleBetween。谢谢你的提示! –