简体   繁体   中英

C# 2D rotation with matrix

I was trying to rotate a simple line counterclockwise. But after the calculations the Y coordinate was always negative. This is my code:

double  degree = 0.785;
       // degree = Convert.ToInt32(degree * Math.PI / 180);
        Graphics g = this.CreateGraphics();

        // Create pen.
        Pen blackPen = new Pen(Color.Black, 3);
        Pen redPen = new Pen(Color.Red, 3);


        // Create points that define line.
        System.Drawing.Point point1 = new System.Drawing.Point(500, 0);
        System.Drawing.Point point2 = new System.Drawing.Point(500, 100);

        // Draw line to screen.
        g.DrawLine(blackPen, point1, point2);
        blackPen.Dispose();

        //Draw ´new Line

        Vector vector1 = new Vector(point2.X, point2.Y);
        Matrix matrix1 = new Matrix(Math.Cos(degree), -Math.Sin(degree), Math.Sin(degree), Math.Cos(degree),0,0);

        Vector result = Vector.Multiply(vector1, matrix1);

        g.DrawLine(redPen,point1.X ,point1.Y,Convert.ToInt32(result.X),Convert.ToInt32(result.Y));

Now I use as for the problems with the rotation:

double  degree = 45;

matrix.RotateAt(degree, point1.X, point1.Y);

That happens because there is no such thing as just "rotation". There is only "rotation around the fixed point" and the movement depends on the selection of that "fixed point". What you do now is effectively rotate around (0,0) and given that your X is 500 , it obviously moves the whole thing up ie in the negative Y area. Unfortunately it is not quite clear around which point you want to rotate the line but anyway Matrix.RotateAt is the method you should look at. So to rotate around one of the ends you may use code like this:

Matrix matrix = new Matrix();
matrix.RotateAt(angleInDegrees, new PointF(point1.X, point1.Y));

Also you don't have to make multiplication yourself. Usually it is better to set the Graphics.Transform directly or using Graphics.MultiplyTransform method.

One more thing, the line

Graphics g = this.CreateGraphics();

is suspicious. If you want to draw something on a Control , you should override its OnPaint method and then get Graphics from the PaintEventArgs.Graphics property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM