Calculate angle from matrix transformation

I have the following line of code: I applied a few rotations to the rectangle without knowing the values ​​(from the number of degrees). Now I want to get the rotation or angle of an element in 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 !! 

This does not seem to be the correct value. I want to get angles from 0 to 360 degrees

+7
source share
3 answers

You can use this:

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

The idea is this:

  • We create tempvector (1,0)
  • We apply the matrix transformation to the vector and get a rotating time vector
  • Calculate the angle between the original and the rotating time vector

You can play with this:

 [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); } 
+9
source

FOR FUTURE REFERENCE:

This will give you the rotation angle of the transformation matrix in radians:

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

and you can convert radians to degrees if you need:

 var degrees = radians * 180 / Math.PI; 
+8
source

Your answers will be in radians, http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/c14fd846-19b9-4e8a-ba6c-0b885b424439/ .

So just convert the values ​​back to degrees using the following:

 double deg = angle * (180.0 / Math.PI); 
+1
source

All Articles