wpf 从矩阵变换计算角度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14125771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calculate angle from matrix transform
提问by Hiren Desai
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.
我有以下代码行:我在不知道值(多少度)的情况下对矩形应用了很少的旋转。现在我想在 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
这似乎不是正确的值。我想获得0 到 360 度的角度
回答by Johan Larsson
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:
这个想法是:
- We create a tempvector (1,0)
- We apply the matrix transform on the vector and get a rotated temp vector
- We calculate the angle between the original and the rotated temp vector
- 我们创建一个临时向量 (1,0)
- 我们对向量应用矩阵变换并得到一个旋转的临时向量
- 我们计算原始和旋转的临时向量之间的角度
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);
}
回答by Eren Ers?nmez
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;
回答by Sean Airey
Your answers will be in radians, http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/c14fd846-19b9-4e8a-ba6c-0b885b424439/.
您的答案将以弧度表示,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);

