【问题标题】:drawing a .bmp from a 2D array with c#使用 c# 从二维数组中绘制 .bmp
【发布时间】:2011-11-03 02:42:34
【问题描述】:

我正在尝试从二维布尔数组中绘制 bmp 图像文件。目标如下,我需要为每个值绘制一个小方块,颜色取决于布尔值,如果为真,它会以给定的颜色绘制,如果为假,它会绘制为白色。 这个想法是基于矩阵创建一个迷宫

我在网上找到的大多数解决方案都是使用 MemoryStream 的一维字节数组,但我没有用我选择的大小绘制一个完整的正方形。

我的主要问题是如何使用 c# 在 bmp 或图像上绘图

提前感谢您的任何建议

【问题讨论】:

  • 你的平台是什么?银光? wpf?表格? ASP.NET? (等)解决方案可能取决于此信息。

标签: c# image bmp


【解决方案1】:

这是一个使用二维数组并保存生成的位图的解决方案。您必须从文本文件中读取迷宫或像我一样手动输入它。您可以使用squareWidthsquareHeight 变量调整图块的大小。使用一维数组也可以,但如果您只是在学习这些东西,可能就不那么直观了。

bool[,] maze = new bool[2,2];
maze[0, 0] = true;
maze[0, 1] = false;
maze[1, 0] = false;
maze[1, 1] = true;
const int squareWidth = 25;
const int squareHeight = 25;
using (Bitmap bmp = new Bitmap((maze.GetUpperBound(0) + 1) * squareWidth, (maze.GetUpperBound(1) + 1) * squareHeight))
{
    using (Graphics gfx = Graphics.FromImage(bmp))
    {
        gfx.Clear(Color.Black);
        for (int y = 0; y <= maze.GetUpperBound(1); y++)
        {
            for (int x = 0; x <= maze.GetUpperBound(0); x++)
            {
                if (maze[x, y])
                    gfx.FillRectangle(Brushes.White, new Rectangle(x * squareWidth, y * squareHeight, squareWidth, squareHeight));
                else
                    gfx.FillRectangle(Brushes.Black, new Rectangle(x * squareWidth, y * squareHeight, squareWidth, squareHeight));
            }
        }
    }
    bmp.Save(@"c:\maze.bmp");
}

【讨论】:

    【解决方案2】:

    我不确定你的输出设计是什么,但这可能会让你开始使用 GDI。

    int boardHeight=120;
    int boardWidth=120;
    int squareHeight=12;
    int squareWidth=12;
    Bitmap bmp = new Bitmap(boardWidth,boardHeight);
    using(Graphics g = Graphics.FromImage(bmp))
    using(SolidBrush trueBrush = new SolidBrush(Color.Blue)) //Change this color as needed
    {
        bool squareValue = true; // or false depending on your array
        Brush b = squareValue?trueBrush:Brushes.White;
        g.FillRectangle(b,0,0,squareWidth,squareHeight);
    }
    

    您将需要根据您对输出图像的要求来扩展它并遍历您的数组,但由于您指出您的主要问题是开始在 .Net 中绘图,希望此示例为您提供必要的基础知识。

    【讨论】:

      猜你喜欢
      • 2019-02-07
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 2018-09-04
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      相关资源
      最近更新 更多