Hugo Alves
Hugo Alves

Reputation: 1555

drawing a .bmp from a 2D array with c#

I'm trying to draw a bmp image file from a 2 dimensional Boolean array. The objective is the following i need to draw a small square for each value and the color depends on the boolean if true it paints in a given color and if false it paints white. the idea is to create a maze based on the matrix

Most solutions i find over the web are with 1 dimensional byte array using MemoryStream but i doesn't paint a full square with a size of my choosing.

My main problem is how to draw on a bmp or an image using c#

thanks in advance for any advice

Upvotes: 2

Views: 2729

Answers (2)

Duck
Duck

Reputation: 401

Here's a solution that uses a 2 dimension array and saves the resulting bitmap. You'll have to either read in the maze from a text file or hand enter it as I have done. You can adjust the size of the tiles with the squareWidth, squareHeight variables. Using a one-dimensional array would also work, but may not be as intuitive if you're just learning about these things.

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

Upvotes: 2

Joshua Marble
Joshua Marble

Reputation: 560

I'm not sure what your output design will be, but this might get you started with 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);
}

You will need to expand this based on your requirements for your output image and to iterate through your array, but since you indicated your main problem was getting started with drawing in .Net, hopefully this example gives you the necessary basics.

Upvotes: 0

Related Questions