Hiren Desai
Hiren Desai

Reputation: 1091

Calculate angle from matrix transform

I have following line of code: I have applied few rotation to the rectangle at without knowing values (of how many degrees). Now I want to get Rotation or angle of 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 seems to be correct value. I want to get angles in 0 to 360 degrees

Upvotes: 8

Views: 9079

Answers (3)

Eren Ersönmez
Eren Ersönmez

Reputation: 39085

FOR FUTURE REFERENCE:

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

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

and you can convert the radians to degrees if you need:

var degrees = radians * 180 / Math.PI;

Upvotes: 12

Johan Larsson
Johan Larsson

Reputation: 17580

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:

  1. We create a tempvector (1,0)
  2. We apply the matrix transform on the vector and get a rotated temp vector
  3. We calculate the angle between the original and the rotated temp vector

You can play around 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);
}

Upvotes: 10

Sean Airey
Sean Airey

Reputation: 6372

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

So simply convert the values back to degrees using the following:

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

Upvotes: 0

Related Questions