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
Given a rotation matrix R, we can compute the Euler angles, ψ, θ, and φ by equating each element in R with the corresponding element in the matrix product Rz(φ)Ry(θ)Rx(ψ). This results in nine equations that can be used to find the Euler angles. Starting with R31, we find R31 = − sin θ.
When you want to transform a point using a transformation matrix, you right-multiply that matrix with a column vector representing your point. Say you want to translate (5, 2, 1) by some transformation matrix A. You first define v = [5, 2, 1, 1]T.
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;
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:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With