2D矩阵的旋转:
NewX = X * Cos(α) - Y * Sin(α)
NewY = X * Sin(α) + Y * Cos(α)
一般在三角函数中使用的是弧度,我们可以通过下面的公式将角度转为弧度:
α = (degrees / 360 * PI)
示例代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace MatrixTransForm { /// <summary> /// 三角形 /// </summary> class Triangle { PointF A, B, C; public Triangle(PointF A, PointF B, PointF C) { this.A = A; this.B = B; this.C = C; } /// <summary> /// 绘制三角形 /// </summary> /// <param name="g"></param> public void Draw(Graphics g) { Pen pen = new Pen(Color.Red); pen.Width = 4; g.DrawLine(pen, A, B); g.DrawLine(pen, B, C); g.DrawLine(pen, C, A); } /// <summary> /// 旋转三角形 /// </summary> /// <param name="degrees">要旋转的角度</param> public void Rotate(int degrees) { // 将角度转为弧度 float angle = (float)(degrees / 360.0f * Math.PI); float newX = (float)(A.X * Math.Cos(angle) - A.Y * Math.Sin(angle)); float newY = (float)(A.X * Math.Sin(angle) + A.Y * Math.Cos(angle)); A.X = newX; A.Y = newY; newX = (float)(B.X * Math.Cos(angle) - B.Y * Math.Sin(angle)); newY = (float)(B.X * Math.Sin(angle) + B.Y * Math.Cos(angle)); B.X = newX; B.Y = newY; newX = (float)(C.X * Math.Cos(angle) - C.Y * Math.Sin(angle)); newY = (float)(C.X * Math.Sin(angle) + C.Y * Math.Cos(angle)); C.X = newX; C.Y = newY; } } }
窗口代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace MatrixTransForm { public partial class Form1 : Form { Triangle t; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (t == null) t = new Triangle(new PointF(0, -100), new PointF(100, 100), new PointF(-100, 100)); Invalidate(); } private void Form1_Paint(object sender, PaintEventArgs e) { if (t != null) { e.Graphics.TranslateTransform(200, 200); t.Draw(e.Graphics); } } private void timer1_Tick(object sender, EventArgs e) { if (t != null) { t.Rotate(1); Invalidate(); } } } }
效果: