Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to draw a tile-map in WPF

Tags:

c#

wpf

In my "game" I will draw a small map (i.e. 10x10 fields). Each field will represent a wall or ground. Depending on the answers to this question, the tiles will be either PNG images or simple color-filled rectangles.

What is your best recommended way to draw such a map in WPF? I want it to be as simple as possible, because the GUI part of this project is not very important, I just want it to be displayed in the center of the window.

Ideas that I have:

  • Canvas + placing multiple Rectangles as children
  • Bitmap rendered by engine, displayed by GUI
  • External library?
like image 615
emesx Avatar asked Mar 26 '12 16:03

emesx


1 Answers

WPF is not so inclined toward drawing as Windows Forms is. WPF is more content-oriented.

The best way to 'draw' something is to generate the map out of existing WPF elements. For example, you could use a Grid or UniformGrid, or even a Canvas to lay out your content. You could programmatically add Images and Rectangles to the map, without worrying about any drawing code.

Here is an example:

UniformGrid grid = new UniformGrid();
grid.Columns = 10;
grid.Rows = 10;
grid.Width = columnWidth * 10;
grid.Height = rowHeight * 10;
for (int x = 0; x < 10; x++)
{
    for (int y = 0; y < 10; y++)
    {
        if (fields[x, y] is SomeImage)
        {
            Image img = new Image();
            img.Source = someImageSource;
            grid.Children.Add(img);
        }
        else
        {
            Rectangle rect = new Rectangle();
            rect.Fill = someColor;
            grid.Children.Add(rect);
        }
    }
}
Canvas.SetLeft(grid, (canvas.Width - grid.Width) / 2);
Canvas.SetTop(grid, (canvas.Height - grid.Height) / 2);
canvas.Children.Add(grid);

You probably won't be able to use that as is, but you can fill in the missing pieces.

I recently did a project similar to this, using a Canvas to lay out TextBlocks, Lines and Buttons. It is efficient and simple, a lot more than I expected.

like image 195
Kendall Frey Avatar answered Nov 17 '22 09:11

Kendall Frey