[英]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)
旋轉,並且假設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
方法,然后從PaintEventArgs.Graphics
屬性獲取Graphics
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.