美好的一天。
下面的代码用于在c#中的齐次坐标中绘制正方形和变换。
缩放和旋转操作正常工作(代码体中注释的字符串),但翻译操作不起作用。看来,T矩阵的最后一行(坐标为[2,0],[2,1],[2,2])不会影响操作。
有人能看到代码的错误吗? 关心,谢谢。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AFFINES02
{
public partial class Form1 : Form
{
double[,] Sq = new double[4,3];
double[,] T = new double [3,3];
private double RadianToDegree(double angle)
{
return Math.PI * angle / 180.0;
}
public Form1()
{
InitializeComponent();
ResizeRedraw = true;
Load += Form1_Load;
Paint += Form1_Paint;
}
private void Form1_Load(object sender, EventArgs e)
{
//Original matrix
Sq[0, 0] = 0;
Sq[0, 1] = 0;
Sq[1, 0] = 50;
Sq[1, 1] = 0;
Sq[2, 0] = 50;
Sq[2, 1] = 50;
Sq[3, 0] = 0;
Sq[3, 1] = 50;
//Transformation matrix
T[0, 0] = 1;
T[0, 1] = 0;
T[0, 2] = 0;
T[1, 0] = 0;
T[1, 1] = 1;
T[1, 2] = 0;
T[2, 0] = 2; //x-translation
T[2, 1] = 2; //y-translation
T[2, 2] = 1;
//T[0, 0] = Math.Cos(RadianToDegree(90)); //0.707; //T[0, 0] = 1;
//T[0, 1] = Math.Sin(RadianToDegree(90));//0.707; //T[0, 1] = 0;
//T[0, 2] = 0; //T[0, 2] = 0;
//T[1, 0] = -(Math.Sin(RadianToDegree(90)));//-0.707; //T[1, 0] = 0;
//T[1, 1] = Math.Cos(RadianToDegree(90));//0.707; //T[1, 1] = 1;
//T[1, 2] = 0; //T[1, 2] = 0;
//T[2, 0] = 0; //T[2, 0] = 0;
//T[2, 1] = 0; //T[2, 1] = 0;
//T[2, 2] = 1; //T[2, 2] = 1;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
double[] b = new double[3];//intermediate matrix
for (int j = 0; j < 4; j++)//cicle for 4 point of square
{
for (int i = 0; i < 3; i++)
{
b[i] = 0;
for (int k = 0; k < 3; k++)
b[i] = b[i] + Sq[j, k] * T[k, i];
}
for (int k = 0; k < 3; k++)
Sq[j, k] = b[k];
}
Graphics gfx = e.Graphics;
Pen skyBluePen = new Pen(Brushes.DeepSkyBlue);
int cx = ClientSize.Width / 2;
int cy = ClientSize.Height / 2;
gfx.DrawLine(skyBluePen, cx, 0, cx, ClientSize.Height);
gfx.DrawLine(skyBluePen, 0, cy, ClientSize.Width, cy);
Pen SqPen = new Pen(Brushes.BlueViolet);
gfx.DrawLine(SqPen, (int)(cx + Sq[0, 0]), (int)(cy - Sq[0, 1]),
(int)(cx + Sq[1, 0]), (int)(cy - Sq[1, 1]));
gfx.DrawLine(SqPen, (int)(cx + Sq[1, 0]), (int)(cy - Sq[1, 1]),
(int)(cx + Sq[2, 0]), (int)(cy - Sq[2, 1]));
gfx.DrawLine(SqPen, (int)(cx + Sq[2, 0]), (int)(cy - Sq[2, 1]),
(int)(cx + Sq[3, 0]), (int)(cy - Sq[3, 1]));
gfx.DrawLine(SqPen, (int)(cx + Sq[3, 0]), (int)(cy - Sq[3, 1]),
(int)(cx + Sq[0, 0]), (int)(cy - Sq[0, 1]));
}
}
}
答案 0 :(得分:0)
我不会自己编码,而是使用System.Drawing.Drawing2D.Matrix代替。你确定,你的矩阵乘法是正确的吗?首先尝试单独测试一个。为什么Sq需要大小为4x3?此外,您可能很容易对矩阵中的行和列感到困惑。您是否尝试过使用T [0,2]和T [1,2]?