Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Rotate a Polygon(Triangle)

I have a method which is to draw a polygon, and then rotate that polygon 90 degrees to the right so that its original top point is now pointing towards the right.

This is the code to draw the polygon(triangle) how ever I'm lost on how to rotate this.

Point[] points = new Point[3];
points[0] = new Point((int)top, (int)top);
points[1] = new Point((int)top - WIDTH / 2, (int)top + HEIGHT);
points[2] = new Point((int)top + WIDTH / 2, (int)top + HEIGHT);
paper.FillPolygon(normalBrush, points);

Thanks in advance.

like image 523
Dan Avatar asked Feb 23 '23 05:02

Dan


2 Answers

http://msdn.microsoft.com/en-us/library/s0s56wcf.aspx#Y609

public void RotateExample(PaintEventArgs e)
{
    Pen myPen = new Pen(Color.Blue, 1);
    Pen myPen2 = new Pen(Color.Red, 1);

    // Draw the rectangle to the screen before applying the transform.
    e.Graphics.DrawRectangle(myPen, 150, 50, 200, 100);

    // Create a matrix and rotate it 45 degrees.
    Matrix myMatrix = new Matrix();
    myMatrix.Rotate(45, MatrixOrder.Append);

    // Draw the rectangle to the screen again after applying the

    // transform.
    e.Graphics.Transform = myMatrix;
    e.Graphics.DrawRectangle(myPen2, 150, 50, 200, 100);
}

You can use TransformPoints method of Matrix class to just rotate the points

like image 199
Muhammad Hasan Khan Avatar answered Feb 27 '23 18:02

Muhammad Hasan Khan


See this informative Wikipedia article for a great explanation of rotation matrices. When rotating 90 degrees we note that cos 90 collapses into zero yielding the following simple transformation where x' and y' are your rotated coordinates and x and y are the previous coordinates.

x' = -y
y' = x

Applying this simple replacement on your example yields the following code. I've also used a shorthand collection initializer expression for added readability.

var points = new[]
{
    new Point(-(int) top, (int) top),
    new Point((int) -(top + HEIGHT), (int) top - WIDTH/2),
    new Point((int) -(top + HEIGHT), (int) top + WIDTH/2)
};

paper.FillPolygon(normalBrush, points);

I also recommend reading up on linear algebra using for example Anton Rorres, et al.

like image 23
vidstige Avatar answered Feb 27 '23 17:02

vidstige