Общие условия выбора системы дренажа: Система дренажа выбирается в зависимости от характера защищаемого...

Автоматическое растормаживание колес: Тормозные устройства колес предназначены для уменьше­ния длины пробега и улучшения маневрирования ВС при...

Графический интерфейс приложения.

2021-04-19 95
Графический интерфейс приложения. 0.00 из 5.00 0 оценок
Заказать работу

Вверх
Содержание
Поиск

 

Рис.1. Созданные пользовательские компоненты

 

Рис.2. Конструктор компоненты.

 

Рис.3. Компонента на форме.

 


 

Рис.4. Ввод значений.

 

Рис.5. Результат работы программы.

 

Рис.6. Содержание текстового файла.

 


 

Исходный текст программы.

Компонента.

MatrixCalc

{partial class matrixCalc: UserControl

{loaded = false;texFont;сheck = false;static List<matrix> matrixList;//Список матрицstatic Mode operationMode = Mode.Default;//текущая операцияstatic Point resolution = new Point(200, 200);//размерность x и ydouble det;matrixCalc()

{();

}void matrixCalc_Load(object sender, EventArgs e)

{= null;= null;= Mode.Default;= true;

}void glControl1_Load(object sender, EventArgs e)

{= true;

}void glControl1_Resize(object sender, EventArgs e)

{(!loaded);

}void обратнаяToolStripMenuItem_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)

{= new List<matrix>();

сheck = false;= Mode.Invert;

}void транспонированиеToolStripMenuItem_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)

{= new List<matrix>();

сheck = false;= Mode.Transpose;

}void определительToolStripMenuItem_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)

{= new List<matrix>();

сheck = false;= Mode.Determinant;

}void умножениеToolStripMenuItem_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)

{= new List<matrix>();

сheck = false;= Mode.Multiplication;

}void сложениеToolStripMenuItem_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)

{= new List<matrix>();

сheck = false;= Mode.Addition;

}void вычитаниеToolStripMenuItem_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)

{= new List<matrix>();

сheck = false;= Mode.Substraction;

}void однаМатрицаToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)

{();mtxCalc = this;f = new Form3(mtxCalc);.ShowDialog();

}void двеМатрицыToolStripMenuItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)

{();mtxCalc = this;f = new Form1(mtxCalc);.ShowDialog();

}void glControlSetting()

{= true;(glControl1);//настраиваем шрифты и opengl= fontSetting(glControl1);.ClearColor(Color.SkyBlue);//Заливка по умолчанию

}void matrixCalc_SizeChanged(object sender, EventArgs e)

{.Width = this.Width;.Height = this.Height - 24;(matrixList!=null)

{.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);(texFont, matrixList[0].mtx);(operationMode!= Mode.Determinant)

{(texFont, matrixList[0].mtx, matrixList[1].mtx);

}.SwapBuffers();

}

}void saveAsTxt()

{data = new dataOperations();sfd = new SaveFileDialog();.DefaultExt = "txt";.Filter = "Matrix textfile|*.txt";.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);(matrixList == null)

{.Show("Матрицы не были введены");;

}(sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)

{.saveAllMatrixTxt(sfd.FileName);(texFont, matrixList[0].mtx);(operationMode!= Mode.Determinant)

{(texFont, matrixList[0].mtx, matrixList[1].mtx);

}.SwapBuffers();

}

}void saveAsMtx()

{data = new dataOperations();sfd = new SaveFileDialog();.DefaultExt = "mtx";.Filter = "Matrix file|*.mtx";.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);(matrixList == null)

{.Show("Матрицы не были введены");;

}(sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)

{.saveAllMatrixMtx(sfd.FileName);(texFont, matrixList[0].mtx);(operationMode!= Mode.Determinant)

{(texFont, matrixList[0].mtx, matrixList[1].mtx);

}.SwapBuffers();

}

}void openFile()

{data = new dataOperations();();od = new OpenFileDialog();.Filter = "Matrix file|*.mtx|Matrix textfile|*.txt";.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);(od.ShowDialog() == System.Windows.Forms.DialogResult.OK)

{p = od.FileName;type = Path.GetExtension(p);(type == ".mtx")

{.readAllMatrixMtx(od.FileName);

}(type == ".txt")

{.readAllMatrixTxt(od.FileName);

}(texFont, matrixList[0].mtx);(operationMode!= Mode.Determinant)

{(texFont, matrixList[0].mtx, matrixList[1].mtx);

}.SwapBuffers();

}

}void glControl1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)

{mtxCalc = this;

сheck = false;worldCoords = convertScreenToWorldCoords(e.X, e.Y);.Y = (resolution.Y - worldCoords.Y);(e.Button == MouseButtons.Right && matrixList!=null)

{(matrixList.Count > 0 && matrixList[0].Contains(worldCoords,30,13)==true)

{(operationMode)//Операции

{Mode.Invert:Mode.Transpose:Mode.Determinant:f3 = new Form3(mtxCalc);.ShowDialog();;Mode.Addition:Mode.Substraction:Mode.Multiplication:f1 = new Form1(mtxCalc);.ShowDialog();;

}

}

}

}void glControl1_Paint(object sender, PaintEventArgs e)

{(matrixList!= null)

{.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);//очищаем поверхность(texFont, matrixList[0].mtx);(operationMode!= Mode.Determinant)

{(texFont, matrixList[0].mtx, matrixList[1].mtx);

}.SwapBuffers();

}

}TextureFont fontSetting(GLControl glControl1)//Для настройки поверхности опегл и шрифтов

{.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);//очищаем поверхность.MatrixMode(MatrixMode.Modelview);.LoadIdentity();

// Настраиваем опенгл для текстуры.InitTexturing();

//Загружаем текстуру со шрифтами

int tex = TexUtil.CreateTextureFromFile(Application.StartupPath + @"\" + "font1.png");

// Создаем объект TextureFont из загруженной текстуры

TextureFont texFont = new TextureFont(tex);texFont;

}static Point convertScreenToWorldCoords(int x, int y)

{[] viewport = new int[4];modelViewMatrix, projectionMatrix;.GetFloat(GetPName.ModelviewMatrix, out modelViewMatrix);.GetFloat(GetPName.ProjectionMatrix, out projectionMatrix);.GetInteger(GetPName.Viewport, viewport);mouse;.X = x;.Y = y;vector = UnProject(ref projectionMatrix, modelViewMatrix, new Size(viewport[2], viewport[3]), mouse);coords = new Point((int)vector.X, (int)vector.Y);coords;

}static Vector4 UnProject(ref Matrix4 projection, Matrix4 view, Size viewport, Vector2 mouse)

{vec;.X = 2.0f * mouse.X / (float)viewport.Width - 1;.Y = 2.0f * mouse.Y / (float)viewport.Height - 1;.Z = 0;.W = 1.0f;viewInv = Matrix4.Invert(view);projInv = Matrix4.Invert(projection);.Transform(ref vec, ref projInv, out vec);.Transform(ref vec, ref viewInv, out vec);(vec.W > float.Epsilon || vec.W < float.Epsilon)

{.X /= vec.W;.Y /= vec.W;.Z /= vec.W;

}vec;

}void drawAllMatrix(TextureFont texFont, double[,] mtx)//для рисования матриц(обратная, определитель, транспонирование)

{font = 20;//размер шрифтаm = matrixList[0].rowCount;//Кол-во строк= new Point(200, 200);(operationMode)

{Mode.Invert:(m > 3)

{.X = m * 60 + 17;.Y = m * 60 + 17;

}

{= new Point(210, 210);

}(сheck == false)

{matrixI = new matrix(matrixOperations.Inverse(mtx).GetLength(0), matrixOperations.Inverse(mtx).GetLength(1));.mtx = matrixOperations.Inverse(mtx);.Add(matrixI);

}.LoadIdentity();.Ortho(0, resolution.X, resolution.Y, 0, -1, 1);.Viewport(0, 0, glControl1.Width, glControl1.Height);[0].Draw("A=",30, 13, texFont, resolution);[1].Draw("A^(-1)=",45, matrixList[0].size.Y + 27, texFont, resolution);;Mode.Transpose:(сheck == false)

{matrixT = new matrix(matrixOperations.Transpose(mtx).GetLength(0), matrixOperations.Transpose(mtx).GetLength(1));.mtx = matrixOperations.Transpose(mtx);.Add(matrixT);

}n = matrixList[0].columnCount;m1 = matrixList[1].rowCount;n1 = matrixList[1].columnCount;(m > 2 || n > 2)

{(n > n1)

{.X = n * 55;

}

{.X = n1 * 55;

}

}.Y = m * 25 + m1 * 25 + 60;.LoadIdentity();.Ortho(0, resolution.X, resolution.Y, 0, -1, 1);.Viewport(0, 0, glControl1.Width, glControl1.Height);[0].Draw("A=",30, 13, texFont, resolution);[1].Draw("AT=",40, matrixList[0].size.Y +27,texFont, resolution);;Mode.Determinant:(сheck == false)

{= matrixOperations.Determinent(mtx);

}(m > 3)

{.X = m * 60;.Y = m * 30 + 40;

}

{= new Point(200, 200);

}.LoadIdentity();.Ortho(0, resolution.X, resolution.Y, 0, -1, 1);.Viewport(0, 0, glControl1.Width, glControl1.Height);[0].Draw("A=",30, 13, texFont, resolution);.WriteStringAt("detA=", font, 18, resolution.Y - matrixList[0].size.Y -25, 0, resolution);.WriteStringAt(Convert.ToString(det), font, 60, resolution.Y - matrixList[0].size.Y - 25, 0, resolution);;

}

сheck = true;

}void drawAllMatrix(TextureFont texFont, double[,] mtx1, double[,] mtx2)//для рисования матриц(умножение, сложение, вычитание)

{(operationMode)

{Mode.Multiplication:("A*B=", texFont, mtx1, mtx2);;Mode.Addition:("A+B=", texFont, mtx1, mtx2);;Mode.Substraction:("A-B=", texFont, mtx1, mtx2);;

}

}void drawOperation(string operation, TextureFont texFont, double[,] mtx1, double[,] mtx2)//для метода выше

{font = 20;//размер шрифта= new Point(200, 200);(сheck == false)

{(operationMode)

{Mode.Multiplication:matrixM = new matrix(matrixOperations.multiplication(mtx1, mtx2).GetLength(0), matrixOperations.multiplication(mtx1, mtx2).GetLength(1));.mtx = matrixOperations.multiplication(mtx1, mtx2);.Add(matrixM);;Mode.Addition:matrixA = new matrix(matrixOperations.addition(mtx1, mtx2).GetLength(0), matrixOperations.addition(mtx1, mtx2).GetLength(1));.mtx = matrixOperations.addition(mtx1, mtx2);.Add(matrixA);;Mode.Substraction:matrixS = new matrix(matrixOperations.subtraction(mtx1, mtx2).GetLength(0), matrixOperations.subtraction(mtx1, mtx2).GetLength(1));.mtx = matrixOperations.subtraction(mtx1, mtx2);.Add(matrixS);;

}

}m = matrixList[0].rowCount;m1 = matrixList[2].rowCount;n1 = matrixList[0].columnCount;n2 = matrixList[1].columnCount;m3 = matrixList[2].rowCount;.X = n1 * 55 + n2 * 55 + 30;.Y = 25 * (m1 + m3) + 60;.LoadIdentity();.Ortho(0, resolution.X, resolution.Y, 0, -1, 1);.Viewport(0, 2, glControl1.Width, glControl1.Height);[0].Draw("A=",30, 13,texFont,resolution);[1].Draw("B=", matrixList[0].size.X + 60,13, texFont, resolution);[2].Draw(operation,30, matrixList[0].size.Y +25, texFont, resolution);

сheck = true;

}

}

Классы.

public abstract class Matrix

{int rowCount;int columnCount;Point size;Matrix()

{= new Point(0, 0);

}public void Draw(int x, int y);

}class Cell: Matrix

{int width;int height;Cell(int w, int h)

{.width = w;.height = h;

}void DrawLine(Point A, Point B)

{.Vertex2(A.X, A.Y);.Vertex2(B.X, B.Y);

}override void Draw(int x0, int y0)

{p1 = new Point(x0, y0);p2 = new Point(x0 + width, y0);p3 = new Point(x0, y0 + height);p4 = new Point(x0 + width, y0 + height);(p1, p2);(p1, p3);(p3, p4);(p4, p2);.X = width;.Y = height;

}

}class matrixTable: Matrix

{Cell cell;x;y;matrixTable(int rowCount, int columnCount)

{= new Cell(45, 25);.rowCount = rowCount;.columnCount = columnCount;

}override void Draw(int x0, int y0)

{= x0;= y0;.Begin(BeginMode.Lines);(int i = 0; i < rowCount; i++)

{(int j = 0; j < columnCount; j++)

{.Draw(x0 + cell.width * j, y0 + cell.height * i);

}

}.X = cell.width * columnCount;.Y = cell.height * rowCount;.End();

}void drawText(TextureFont texFont, Point resolution)

{(int i = 0; i < rowCount; i++)

{text = new cellText(45, 25, Convert.ToString(i));.drawVertical(x, resolution.Y - y - cell.height * i - 25, texFont, resolution);

}(int j = 0; j < columnCount; j++)

{text = new cellText(45, 25, Convert.ToString(j));.drawHorizontal(x + cell.width * j, resolution.Y - y + 7, texFont, resolution);

}

}

}class matrix: Matrix

{double[,] mtx;mtxTab;matrix(int rowCount, int columnCount)

{.rowCount = rowCount;.columnCount = columnCount;= new double[rowCount, columnCount];= new matrixTable(rowCount, columnCount);= new Point(45 * columnCount, 25 * rowCount);

}void Draw(string operation, int x0, int y0, TextureFont texFont, Point resolution)

{y = resolution.Y - 11 - y0;M = Convert.ToDouble(mtx.GetLength(1));

double dx = 0;//Интервал между цифрамиdy = 0;//Интервал между строками

for (int i = 0; i < mtx.GetLength(0); i++)

{(int j = 0; j < mtx.GetLength(1); j++)

{= dx + 45;.WriteStringAt(Convert.ToString(mtx[i, j]), 20, x0 + dx - 20, y + dy, 0, resolution);

}= dx - 45 * (M);= dy - 25;

}text = new matrixText(operation, rowCount, columnCount);.draw(x0, y0, texFont, resolution);.Disable(EnableCap.Texture2D);(x0, y0);.Enable(EnableCap.Texture2D);.drawText(texFont, resolution);

}override void Draw(int x0, int y0)

{.Draw(x0, y0);

}void setMatrix(DataGridView dataGridView1)//Записывает матрицу в список

{(int i = 0; i < rowCount; i++)

{(int j = 0; j < columnCount; j++)

{[i, j] = Convert.ToDouble(dataGridView1.Rows[i].Cells[j].Value);

}

}

}bool Contains(Point point, int x0, int y0)

{contains = false;GraphicsPathRectangle = new GraphicsPath();RectangleDraw = new Rectangle(x0, y0, size.X, size.Y);.AddRectangle(RectangleDraw);(GraphicsPathRectangle.IsVisible(point))

{= true;

}contains;

}

}class matrixText: matrix

{string text;int width;int height;matrixText(string text, int rowCount, int columnCount)

: base(rowCount, columnCount)

{.text = text;= new Point(45 * columnCount, 25 * rowCount);

}Point calculateLocation()

{location = new Point(0, 0);.X = this.size.X - size.X - 20;.Y = this.size.Y / 2;location;

}

//x,y - координаты таблицыvoid draw(int x, int y, TextureFont texFont, Point resolution)

{.WriteStringAt(text, 20, x - 18, resolution.Y - y, 0, resolution);

}

}class cellText: Cell

{string text;cellText(int width, int height, string text)

: base(width, height)

{.text = text;

}void drawVertical(int x, int y, TextureFont texFont, Point resolution)

{.WriteStringAt(text, 10, x - 4, y + (this.height / 2), 0, resolution);

}void drawHorizontal(int x, int y, TextureFont texFont, Point resolution)

{.WriteStringAt(text, 10, x + (this.width / 2), y, 0, resolution);

}

}

public static class matrixOperations

{

#region//Умножение, сложение, вычитаниеstatic double[,] multiplication(double[,] matrix1, double[,] matrix2)//Умножение

{(matrix1.GetLength(1)!= matrix2.GetLength(0)) throw new Exception("Матрицы нельзя перемножить");[,] r = new double[matrix1.GetLength(0), matrix2.GetLength(1)];(int i = 0; i < matrix1.GetLength(0); i++)

{(int j = 0; j < matrix2.GetLength(1); j++)

{(int k = 0; k < matrix2.GetLength(0); k++)

{[i, j] += matrix1[i, k] * matrix2[k, j];

}

}

}r;

}static double[,] addition(double[,] matrix1, double[,] matrix2)//Сложение

{[,] r = new double[matrix1.GetLength(0), matrix2.GetLength(1)];(matrix1.GetLength(0)!= matrix2.GetLength(0) && matrix1.GetLength(1)!= matrix2.GetLength(1)) throw new Exception("Матрицы нельзя сложить");(int i = 0; i < matrix1.GetLength(0); i++)

{(int j = 0; j < matrix2.GetLength(1); j++)

{[i, j] = matrix1[i, j] + matrix2[i, j];

}

}r;

}static double[,] subtraction(double[,] matrix1, double[,] matrix2)//Вычитание

{[,] r = new double[matrix1.GetLength(0), matrix2.GetLength(1)];(matrix1.GetLength(0)!= matrix2.GetLength(0) && matrix1.GetLength(1)!= matrix2.GetLength(1)) throw new Exception("Матрицы нельзя вычесть");(int i = 0; i < matrix1.GetLength(0); i++)

{(int j = 0; j < matrix2.GetLength(1); j++)

{[i, j] = matrix1[i, j] - matrix2[i, j];

}

}r;

}

#endregion

#region//Транспонирование, обратная, определитель

public static double[,] Transpose(double[,] mtx)

{[,] TransposeMatrix = new double[mtx.GetLength(1), mtx.GetLength(0)];(int i = 0; i < TransposeMatrix.GetLength(0); i++)(int j = 0; j < TransposeMatrix.GetLength(1); j++)[i, j] = mtx[j, i];TransposeMatrix;

}static double[,] Minor(double[,] matrix, int iRow, int iCol)

{[,] minor = new double[matrix.GetLength(0) - 1, matrix.GetLength(1) - 1];m = 0, n = 0;(int i = 0; i < matrix.GetLength(0); i++)

{(i == iRow);= 0;(int j = 0; j < matrix.GetLength(1); j++)

{(j == iCol);[m, n] = matrix[i, j];++;

}++;

}minor;

}static double Determinent(double[,] matrix)

{det = 0;(matrix.GetLength(0)!= matrix.GetLength(1))

MessageBox.Show("Матрица не квадратная");

if (matrix.GetLength(0) == 1)matrix[0, 0];(int j = 0; j < matrix.GetLength(1); j++)+= (matrix[0, j] * Determinent(Minor(matrix, 0, j)) * (int)System.Math.Pow(-1, 0 + j));det;

}static double[,] Adjoint(double[,] matrix)

{(matrix.GetLength(0)!= matrix.GetLength(1))new Exception("Матрица не квадратная");[,] AdjointMatrix = new double[matrix.GetLength(0), matrix.GetLength(1)];(int i = 0; i < matrix.GetLength(0); i++)(int j = 0; j < matrix.GetLength(1); j++)[i, j] = Math.Pow(-1, i + j) * Determinent(Minor(matrix, i, j));= Transpose(AdjointMatrix);AdjointMatrix;

}static double[,] Inverse(double[,] matrix)

{[,] temp = Adjoint(matrix);[,] temp1 = new double[temp.GetLength(0), temp.GetLength(1)];

if (Determinent(matrix) == 0).Show("Матрица вырождена, обратной не существует");

for (int i = 0; i < temp.GetLength(0); i++)

{(int j = 0; j < temp.GetLength(1); j++)

{[i, j] = Math.Round(temp[i, j] / Determinent(matrix), 3);

}

}temp1;

}

#endregion

}


Поделиться с друзьями:

Типы оградительных сооружений в морском порту: По расположению оградительных сооружений в плане различают волноломы, обе оконечности...

Археология об основании Рима: Новые раскопки проясняют и такой острый дискуссионный вопрос, как дата самого возникновения Рима...

Механическое удерживание земляных масс: Механическое удерживание земляных масс на склоне обеспечивают контрфорсными сооружениями различных конструкций...

История развития пистолетов-пулеметов: Предпосылкой для возникновения пистолетов-пулеметов послужила давняя тенденция тяготения винтовок...



© cyberpediasu.com 2017-2026 - Не является автором материалов. Исключительное право сохранено за автором текста.
Если вы не хотите, чтобы данный материал был у нас на сайте, перейдите по ссылке: Нарушение авторских прав. Мы поможем в написании вашей работы!

0.017 с.