2013-01-19 141 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。謝謝你的提示! –