附:转换类源代码
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestDraw
{
class MyTransform
{
private MyMatrix M = new MyMatrix(); //当前的转换矩阵
//平移
public void Translate(float dx, float dy)
{
float[,] K = {
{1,0,dx},
{0,1,dy},
{0,0,1}
};
this.M = this.M.IR(new MyMatrix(K));
}
//缩放
public void Scale(float sx, float sy)
{
float[,] K = {
{sx, 0, 0},
{0, sy, 0},
{0, 0, 1}
};
this.M = this.M.IR(new MyMatrix(K));
}
//旋转
public void Rotate(float sita)
{
float[,] K = {
{(float)Math.Cos(sita), -(float)Math.Sin(sita), 0},
{(float)Math.Sin(sita), (float)Math.Cos(sita), 0},
{0,0,1}
};
this.M = this.M.IR(new MyMatrix(K));
}
//重置转换矩阵
public void Rest()
{
this.M = new MyMatrix();
}
//计算新坐标
public PointF CalculatePoint(PointF jmP)
{
MyPoint newP = this.M.IR(new MyPoint(jmP.X, jmP.Y));
return new PointF(newP.P[0], newP.P[1]);
}
private MyPoint CalculatePoint(MyPoint jmP)
{
return this.M.IR(jmP);
}
}
//点矩阵
class MyPoint
{
public Single[] P = {0,0,1};
public MyPoint(float x, float y)
{
P[0] = x;
P[1] = y;
}
}
//转换矩阵
class MyMatrix
{
public Single[,] K = {
{1,0,0},
{0,1,0},
{0,0,1}
};
public MyMatrix()
{
}
public MyMatrix(Single[,] K)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
this.K[i,j] = K[i,j];
}
}
}
//本矩阵 x R
public MyMatrix IR(MyMatrix R)
{
Single[,] result = new float[3, 3];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
result[i, j] = this.K[i, 0] * R.K[0, j] + this.K[i, 1] * R.K[1, j] + this.K[i, 2] * R.K[2, j];
}
}
return new MyMatrix(result);
}
//本矩阵 x P
public MyPoint IR(MyPoint P)
{
Single[] result = new float[3];
for (int i = 0; i < 3; i++)
{
result[i] = this.K[i, 0] * P.P[0] + this.K[i, 1] * P.P[1] + this.K[i, 2] * P.P[2];
}
return new MyPoint(result[0], result[1]);
}
//L x 本矩阵
public MyMatrix LI(MyMatrix L)
{
return L.IR(this);
}
}
}
测试源代码:
using System.Drawing;
using System.Windows.Forms;
namespace TestDraw
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private MyTransform transform = new MyTransform();
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
//建模坐标系中四个点
PointF p1 = new PointF(0, 0);
PointF p2 = new PointF(5, 0);
PointF p3 = new PointF(5, 2);
PointF p4 = new PointF(0, 2);
绘图坐标系向建模坐标系转变
//transform.Translate(100, 100);
//transform.Scale(1, -1);
//transform.Scale(10, 10);
//transform.Rotate((float)(3.14 / 6.0));
计算点在绘图坐标系中的坐标
//PointF np1 = transform.CalculatePoint(p1);
//PointF np2 = transform.CalculatePoint(p2);
//PointF np3 = transform.CalculatePoint(p3);
//PointF np4 = transform.CalculatePoint(p4);
绘制矩形
//g.DrawLines(Pens.Red, new PointF[]{np1, np2, np3, np4, np1});
//transform.Rest();
g.TranslateTransform(100, 100);
g.ScaleTransform(1, -1);
g.ScaleTransform(10, 10);
g.RotateTransform(30);
g.DrawLines(new Pen(Color.Red, 1/10), new PointF[] { p1, p2, p3, p4, p1 });
g.ResetTransform();
}
}
}