2013-01-02 153 views
7

我有以下的代碼行: 我已經在矩形上應用了少量旋轉,而不知道數值(多少度)。現在我想要在2D中獲得元素的旋轉或角度。從矩陣變換計算角度

Rectangle element = (Rectangle)sender; 
MatrixTransform xform = element.RenderTransform as MatrixTransform; 
Matrix matrix = xform.Matrix; 
third.Content = (Math.Atan(matrix.M21/matrix.M22)*(180/Math.PI)).ToString(); 

and the matrix is like following 
|M11 M12 0| 
|M21 M22 0| 
|dx dy 1| which is Transformation Matrix I guess !! 

這似乎不是正確的值。 我想要在角度0到360度

+0

我想這是一個變換矩陣。 –

+0

是的,它是C#中Transformation Matrix和IT類型的MatrixTransform。 我想在應用轉換後獲得角度。 –

回答

9

您可以使用此:

var x = new Vector(1, 0); 
Vector rotated = Vector.Multiply(x, matrix); 
double angleBetween = Vector.AngleBetween(x, rotated); 

的理念是:

  1. 我們創建了一個tempvector( 1,0)
  2. 我們對矢量應用矩陣變換,得到一個旋轉的臨時矢量
  3. 我們計算原始和旋轉臨時矢量之間的角度

可以玩弄這樣的:

[TestCase(0,0)] 
[TestCase(90,90)] 
[TestCase(180,180)] 
[TestCase(270,-90)] 
[TestCase(-90, -90)] 
public void GetAngleTest(int angle, int expected) 
{ 
    var matrix = new RotateTransform(angle).Value; 
    var x = new Vector(1, 0); 
    Vector rotated = Vector.Multiply(x, matrix); 
    double angleBetween = Vector.AngleBetween(x, rotated); 
    Assert.AreEqual(expected,(int)angleBetween); 
} 
+0

感謝人們的即時回覆。 –

8

供日後參考:

這會給你一個弧度變換矩陣的旋轉角度:

var radians = Math.Atan2(matrix.M21, matrix.M11); 

,你可以將弧度轉換爲度,如果你需要:

var degrees = radians * 180/Math.PI;