将矩阵转换为颜色网格

时间:2012-11-17 16:53:05

标签: c# colors matrix console-application converter

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

这甚至可以在控制台应用程序中完成,如果是这样,怎么办?如果没有,我需要在Windows窗体应用程序中使用它?

2 个答案:

答案 0 :(得分:1)

只需创建一个52x42-px位图,然后使用与矩阵值对应的颜色填充它。

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");
}

答案 1 :(得分: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(...);