代码之家  ›  专栏  ›  技术社区  ›  user19440

C#2D矩阵旋转

  •  0
  • user19440  · 技术社区  · 7 年前

    我试着逆时针旋转一条简单的线。但在计算之后,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);
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   SergGr    7 年前

    之所以会这样,是因为根本不存在所谓的“旋转”。只有“围绕固定点旋转”,移动取决于“固定点”的选择。现在要做的是有效地旋转 (0,0) 考虑到你的 X 500 很明显,它会使整个事情向上发展,也就是说,向上发展 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 方法,然后获取 Graphics PaintEventArgs.Graphics 所有物