Get coordinates after rotation
I have a usercontrol which contains a rectangle and 2 ellipses on the left and right edge of the rectangle. I am intrested in finding out the coordinates of the user control after a translate and rotation rendertransform has occured.
The user control is contained in a canvas.
EDIT: After searching the internet for a while i was able to find the answer to my question here http://forums.silverlight.net/forums/p/136759/305241.aspx so I thought i'd post the link for other people having this issue开发者_如何学C.
I've marked Tomas Petricek's post as an answer because it was the closest one to the solution.
If you want to implement the calculation yourself, then you can use the following method to calculate a location of a point after rotation (by a specified number of degrees):
public Point RotatePoint(float angle, Point pt) {
var a = angle * System.Math.PI / 180.0;
float cosa = Math.Cos(a), sina = Math.Sin(a);
return new Point(pt.X * cosa - pt.Y * sina, pt.X * sina + pt.Y * cosa);
}
In general, you can represent transformations as matrices. To compose transformations, you'd just multiply the matrices, so this is a very composable solution. The matrix to represent rotation contains the sin and cos values from the method above. See Rotation matrix (and Transformation matrix) on Wikipedia.
You rotate a 2D point [4,6] 36 degrees around the origin. What is the new location of the point?
Solution:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Origin of the point
Point myPoint = new Point(4, 6);
// Degrees to rotate the point
float degree = 36.0F;
PointF newPoint = RotatePoint(degree, myPoint);
System.Console.WriteLine(newPoint.ToString());
System.Console.ReadLine();
}
public static PointF RotatePoint(float angle, Point pt)
{
var a = angle * System.Math.PI / 180.0;
float cosa = (float)Math.Cos(a);
float sina = (float)Math.Sin(a);
PointF newPoint = new PointF((pt.X * cosa - pt.Y * sina), (pt.X * sina + pt.Y * cosa));
return newPoint;
}
}
}
Extension methods for those who want to rotate around non zero center:
public static class VectorExtentions
{
public static Point Rotate(this Point pt, double angle, Point center)
{
Vector v = new Vector(pt.X - center.X, pt.Y - center.Y).Rotate(angle);
return new Point(v.X + center.X, v.Y + center.Y);
}
public static Vector Rotate(this Vector v, double degrees)
{
return v.RotateRadians(degrees * Math.PI / 180);
}
public static Vector RotateRadians(this Vector v, double radians)
{
double ca = Math.Cos(radians);
double sa = Math.Sin(radians);
return new Vector(ca * v.X - sa * v.Y, sa * v.X + ca * v.Y);
}
}
Use Transform method of the RotateTransform object - give it the point with coordinates you wish to transform and it will rotate it.
精彩评论