2

I have list of points containing x and y locations of a page. I want to apply rotation on all these points relative to any pivot point of page (currently lets assume its center).

var points = new List<Point>();
points.Add(1,1);
points.Add(15,18);
points.Add(25,2);
points.Add(160,175);
points.Add(150,97);

const int pageHeight = 300;
const int pageWidth = 400;
var pivotPoint = new Point(200, 150); //Center

var angle = 45; // its in degree.

// Apply rotation.

Do I need some formula here?

fhnaseer
  • 7,159
  • 16
  • 60
  • 112

3 Answers3

6
public static Point Rotate(Point point, Point pivot, double angleDegree)
{
    double angle = angleDegree * Math.PI / 180;
    double cos = Math.Cos(angle);
    double sin = Math.Sin(angle);
    int dx = point.X - pivot.X;
    int dy = point.Y - pivot.Y;
    double x = cos * dx - sin * dy + pivot.X;
    double y = sin * dx + cos * dy + pivot.X;

    Point rotated = new Point((int)Math.Round(x), (int)Math.Round(y));
    return rotated;
}
static void Main(string[] args)
{
    Console.WriteLine(Rotate(new Point(1, 1), new Point(0, 0), 45));
}
Ahmed KRAIEM
  • 10,267
  • 4
  • 30
  • 33
  • 2
    Regarding this line: double y = sin * dx + cos * dy + pivot.X; Do you mean: double y = sin * dx + cos * dy + pivot.Y; ? – lagouyn Jan 13 '17 at 18:26
3

If you have a large number of points to rotate, you might want to precompute the rotation matrix…

[C  -S  U]
[S   C  V]
[0   0  1]

…where…

C = cos(θ)
S = sin(θ)
U = (1 - C) * pivot.x + S * pivot.y
V = (1 - C) * pivot.y - S * pivot.x

You then rotate each point as follows:

rotated.x = C * original.x - S * original.y + U;
rotated.x = S * original.x + C * original.y + V;

The above formula is the result of combining three transforms…

rotated = translate(pivot) * rotate(θ) * translate(-pivot) * original

…where…

translate([x y]) = [1 0 x]
                   [0 1 y]
                   [0 0 1]

rotate(θ) = [cos(θ) -sin(θ) 0]
            [sin(θ)  cos(θ) 0]
            [  0       0    1]
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
1

if u rotate a point(x,y) around point (x1,y1) by an angle some a then you need a formula...

x2 = cos(a) * (x-x1) - sin(a) * (y-y1) + x1
y2 = sin(a) * (x-x1) + cos(a) * (y-y1) + y1
Point newRotatedPoint = new Point(x2,y2)
Gopesh Sharma
  • 6,730
  • 4
  • 25
  • 35