繁体   English   中英

带矩阵的C#2D旋转

[英]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));

现在,我使用轮换问题:

double  degree = 45;

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

发生这种情况是因为没有“旋转”之类的东西。 只有“围绕固定点旋转”,并且移动取决于该“固定点”的选择。 现在,您要做的就是有效地绕(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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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