从一个二维数组用c#绘制一个.bmp#
问题描述:
我试图从2维布尔数组中绘制一个bmp图像文件。目标是以下我需要为每个值绘制一个小方形,并且颜色取决于布尔值,如果为true,则以给定颜色绘制,如果为false,则绘制白色。 这个想法是创建一个基于矩阵的迷宫从一个二维数组用c#绘制一个.bmp#
我在网上找到的大多数解决方案都是使用MemoryStream的1维字节数组,但是我并没有绘制出一个大小与我选择的完整正方形。
我的主要问题是如何在一个bmp或图像使用C#绘制
先感谢您的任何意见
答
下面是使用2维数组并保存结果位图的解决方案。您必须从文本文件中读取迷宫,或者像我一样手动输入。您可以使用squareWidth
,squareHeight
变量来调整贴图的大小。使用一维数组也可以,但如果您刚刚了解这些内容,可能不那么直观。
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");
}
答
我不知道你的输出设计将是什么,但是这可能让你从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绘画,希望这个例子给你必要的基础知识。
你的平台是什么? Silverlight的? WPF?的WinForms? asp.net? (等)解决方案可能取决于此信息。 –