【问题标题】:Converting a Matrix to a grid of colors将矩阵转换为颜色网格
【发布时间】:2012-11-06 02:59:45
【问题描述】:

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

这甚至可以在控制台应用程序中完成吗?如果可以,怎么做?如果不是,我需要什么才能让它在 Windows 窗体应用程序中工作?

【问题讨论】:

    标签: c# colors matrix console-application converter


    【解决方案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");
    }
    

    【讨论】:

    • 谢谢!需要进行一些调整才能使所有内容都适合我的项目,但我在此过程中学到了很多东西,这些代码段非常有用 =)
    【解决方案2】:

    考虑使用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(...);
    

    【讨论】:

      猜你喜欢
      • 2015-08-18
      • 1970-01-01
      • 2021-11-20
      • 2018-07-18
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多