类似于matlab的imagesc python的plt.imshow
最基础的功能
using System;
using System.Drawing;
using System.Windows.Forms;
public class MatrixVisualizationForm : Form
{
private int[,] matrix; // 用于存储矩阵数据的二维数组
public MatrixVisualizationForm()
{
this.ClientSize = new Size(72 * 20 + 20, 42 * 20 + 20); // 设置窗体大小以适应矩阵
InitializeMatrix();
this.Paint += new PaintEventHandler(Form_Paint);
}
private void InitializeMatrix()
{
// 初始化一个70x40的矩阵
matrix = new int[40, 70];
for (int i = 0; i < 40; i++)
{
for (int j = 0; j < 70; j++)
{
matrix[i, j] = (i + j) % 10; // 填充一些示例数据
}
}
}
private void Form_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
int cellSize = 20; // 每个矩阵单元的大小
int padding = 0; // 矩阵边缘的填充
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
// 根据矩阵中的值设置颜色,这里简单使用值的大小决定颜色的深浅
Brush brush = new SolidBrush(Color.FromArgb(matrix[i, j] * 25, matrix[i, j] * 25, matrix[i, j] * 25));
g.FillRectangle(brush, padding + j * (cellSize + padding), padding + i * (cellSize + padding), cellSize, cellSize);
}
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MatrixVisualizationForm());
}
}
接下来使其适应窗口尺寸变化
using System;
using System.Drawing;
using System.Windows.Forms;
public class MatrixVisualizationForm : Form
{
private int[,] matrix; // 用于存储矩阵数据的二维数组
public MatrixVisualizationForm()
{
InitializeMatrix();
this.Paint += new PaintEventHandler(Form_Paint);
this.Resize += new EventHandler(Form_Resize); // 添加窗体大小改变事件处理
}
private void InitializeMatrix()
{
// 初始化一个70x40的矩阵
matrix = new int[40, 70];
for (int i = 0; i < 40; i++)
{
for (int j = 0; j < 70; j++)
{
matrix[i, j] = (i + j) % 10; // 填充一些示例数据
}
}
}
private void Form_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
DrawMatrix(g);
}
private void Form_Resize(object sender, EventArgs e)
{
this.Invalidate(); // 触发重绘
}
private void DrawMatrix(Graphics g)
{
int cellSize = Math.Min(this.ClientSize.Width / 70, this.ClientSize.Height / 40); // 根据窗体大小动态计算单元格大小
int padding = 0; // 矩阵边缘的填充
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
// 根据矩阵中的值设置颜色,这里简单使用值的大小决定颜色的深浅
Brush brush = new SolidBrush(Color.FromArgb(matrix[i, j] * 25, matrix[i, j] * 25, matrix[i, j] * 25));
g.FillRectangle(brush, padding + j * (cellSize + padding), padding + i * (cellSize + padding), cellSize, cellSize);
}
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MatrixVisualizationForm());
}
}