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 Rectangle
s as childrenWPF 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 Image
s and Rectangle
s 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 TextBlock
s, Line
s and Button
s. It is efficient and simple, a lot more than I expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With