C#带矩阵的2D旋转

时间:2018-01-19 16:23:20

标签: c# math graphics linear-algebra

我试图逆时针旋转一条简单的线。但是在计算之后,Y坐标总是负的。这是我的代码:

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));

现在我用旋转问题:

double  degree = 45;

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

1 个答案:

答案 0 :(得分:0)

之所以发生这种情况,是因为没有"旋转"。在固定点周围只有"旋转"并且运动取决于选择那个"固定点"。您现在所做的是有效地围绕(0,0)旋转,并且鉴于您的X500,它显然会将整个事情向上移动,即在负Y区域。不幸的是,你想要在哪一点上旋转线并不是很清楚,但无论如何Matrix.RotateAt是你应该看的方法。因此,要绕其中一端旋转,您可以使用以下代码:

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

此外,您不必自己进行乘法运算。通常最好直接设置Graphics.Transform或使用Graphics.MultiplyTransform方法。

还有一件事,

Graphics g = this.CreateGraphics();

很可疑。如果您想在Control上绘制内容,则应覆盖其OnPaint方法,然后从PaintEventArgs.Graphics属性中获取Graphics