2012-11-17 152 views
0

我目前正在C#中制作一个控制台应用程序(将在未来转到Windows窗体应用程序,如果需要,很快)。我当前的目标是将矩阵(当前大小为52x42)作为图像导出(位图,jpeg,png,我很灵活),其中矩阵(0,1,2,3)中的每个值都被描绘为一个白色,黑色,蓝色或红色正方形,大小为20px x 20px,网格宽度为1px,分隔每个“单元格”。将矩阵转换为颜色网格

这甚至可以在控制台应用程序中完成,如果是这样的话?如果没有,我需要什么才能让它在Windows窗体应用程序中工作?

回答

1

只需创建一个52x42像素的位图并使用对应于您的矩阵值的颜色填充它。

using System.Drawing; 

void SaveMatrixAsImage(Matrix mat, string path) 
{ 
    using (var bmp = new Bitmap(mat.ColumnCount, mat.RowCount)) 
    { 
     for (int r = 0; r != mat.RowCount; ++r) 
     for (int c = 0; c != mat.ColumnCount; ++c) 
      bmp.SetPixel(c, r, MakeMatrixColor(mat[r, c])); 
     bmp.Save(path); 
    } 
} 

Color MakeMatrixColor(int n) 
{ 
    switch (n) 
    { 
     case 0: return Color.White; 
     case 1: return Color.Black; 
     case 2: return Color.Blue; 
     case 3: return Color.Red; 
    } 
    throw new InvalidArgumentException("n"); 
} 
+0

谢谢!我们花了一点时间来调整一切以适应我的项目,但是我在这个过程中学到了很多东西,而这些代码段非常有用=) – Zach

1

考虑使用Graphics对象,该对象允许您绘制线条和矩形等形状。这比绘制单个像素更快

using (var bmp = new Bitmap(mat.ColumnCount, mat.RowCount)) { 
    using (var g = Graphics.FromImage(bmp)) { 
     .... 
     g.FillRectangle(Brushes.Red, 0, 0, 20, 20); 
     .... 
    } 
} 
bmp.Save(...);