C# 二维矩阵旋转

C# 2D rotation with matrix

我试图逆时针旋转一条简单的线。但经过计算,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));

现在我用as来解决旋转的问题:

double  degree = 45;

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

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

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

而且你不必自己做乘法。通常设置Graphics.Transform directly or using Graphics.MultiplyTransform方法比较好。

还有一件事,线

Graphics g = this.CreateGraphics();

可疑。如果你想在 Control 上画东西,你应该覆盖它的 OnPaint method and then get Graphics from the PaintEventArgs.Graphics 属性.