Search code examples
c#rotationcoordinatestrigonometrypoint

How can I rotate one point in any degrees?


I'm working with C# program and I've been trying to rotate one point (x,y) to any degree, but I can not find the better solution i got this function:

private Point RotateCoordinates(int degrees, double x, double y)
    {
        Point coordinate = new Point();
        if (degrees == 0 || degrees == 360)
        {
            coordinate.X = x;
            coordinate.Y = y;
        }
        else if (degrees == 90)
        {
            coordinate.X = y.SetNegativeValues();
            coordinate.Y = x;
        }
        else if (degrees == 180)
        {
            coordinate.X = x.SetNegativeValues();
            coordinate.Y = y.SetNegativeValues();
        }
        else if (degrees == 270)
        {
            coordinate.X = y;
            coordinate.Y = x.SetNegativeValues();
        }
        return coordinate;
    }

As you can see this function works fine for 90, 180, and 270 degrees. But the problem is when I have to rotate it 55, 80 degrees or whatever other degree. Some one who can tell me how to implement any rotation?


Solution

  • If you want to know the exact math then you should search for 2D rotation matrix examples. You don't really need to know the math, though, because simple rotations are built into the .Net framework.

    First, add a reference to the WindowsBase assembly if you don't already have one. To perform a 2D rotation you'll need System.Windows.Vector and System.Windows.Media.Matrix.

    Example:

    using System.Windows;
    using System.Windows.Media;
    ...
    var originalPoint = new Vector(10, 0);
    var transform = Matrix.Identity;
    transform.Rotate(45.0); // 45 degree rotation
    var rotatedPoint = originalPoint * transform;
    

    The math for 2D rotations is actually quite simple, so using two new object types might seem like overkill. But the advantage of Matrix transformations is that you can combine multiple transformations into a single matrix if you need to.