by Cameron Albert
23. November 2009 12:52
Bill Reiss posted an interesting article and code the other day concerning the WriteableBitmap class and some extension methods. I downloaded the code and wrote a tiling map control using the WriteableBitmap class for my multi-player role playing game. Here is a snippet of the important piece of code that does the rendering:
1: private void RenderMap()
2: {
3: var xPos = _center.X - _halfX;
4: var yPos = _center.Y - _halfY;
5:
6: for (int y = 0; y < _numTilesY; y++)
7: {
8: for (int x = 0; x < _numTilesX; x++)
9: {
10: var tile = _tiles[new Point3(xPos, yPos, _zIndex)];
11: var terrain = Game.Terrain.Where(t => t.ID == tile.Terrain).FirstOrDefault();
12: if (terrain == null)
13: terrain = Game.GetDefaultTerrain();
14:
15: _surface.Blit(new Point(x * TileWidth, y * TileHeight),
16: _tileImage,
17: _tileRect,
18: terrain.GetColor(),
19: BlendMode.AlphaBlend);
20: xPos++;
21: }
22: xPos = _center.X - _halfX;
23: yPos++;
24: }
25:
26: _surface.Invalidate();
27: }
The _surface variable is just a WriteableBitmap instance initialized to the width and height of the map control. The _tiles variable holds a list of the map tiles in range of the _center position. The xPos and yPos are the world coordinates and the terrain instance just holds the color to paint the tile.
The end result looks something like this:
