I'm currently working on a tiled map editor with WPF using canvas for drawing, but for some reason it's not working with a loop.
I've generated a 160px160p map basing on 16x16 tiles. When I try to add them in a loop it doesn't add them.
public void DrawFullMap()
{
for (int i = 0; i < cMap.mapFile.lMap.Count; i++ )
{
MapPoint mp = cMap.mapFile.lMap[i];
pWindow.DrawOnCanvas(mp.x, mp.y, tileWidth, tileHeight, mp.iTileID);
}
}
private void DrawOnCanvas(int x, int y, int tileWidth, int tileHeight, int index)
{
if (editor != null)
{
Image imgAdd = new Image();
imgAdd.Source = editor.Tileset[index];
imgAdd.Width = tileWidth;
imgAdd.Height = tileHeight;
imgAdd.Margin = new Thickness(x * tileWidth, y * tileHeight, 0, 0);
cvMap.Children.Add(imgAdd);
// Textbox for debug
tbdbg.Text += "X: " + x + " Y:" + y + " Tile:" + index + "\n";
}
}
On use, the textbox I've created should contain all the tiles I want to add, and it does, but for some reason the canvas remains empty (or only adds 1-4 tiles, depends on the canvas size). click for example
When trying to add them manually (MouseEvent) it's working fine, only the loop is causing issues. Why?
EDIT: Changed the margin to SetTop & SetLeft, adding the function for generating the map
private void DrawOnCanvas(int x, int y, int tileWidth, int tileHeight, int index)
{
if (editor != null)
{
Image imgAdd = new Image()
{
Width = tileWidth,
Height = tileHeight,
Source = editor.Tileset[index],
};
Canvas.SetTop(imgAdd, y * tileHeight);
Canvas.SetLeft(imgAdd, x * tileWidth);
cvMap.Children.Add(imgAdd);
// Textbox for debug
tbdbg.Text += "X: " + x + " Y:" + y + " Tile:" + index + "\n";
}
}
public void CreateMapfile(int width, int height)
{
mapFile = new Map();
mapFile.iWidth = width;
mapFile.iHeight = height;
mapFile.lMap = new List<MapPoint>();
for(int i = 0; i < height; i+=16)
{
for(int j = 0; j < width; j+=16)
{
MapPoint mp = new MapPoint();
mp.x = i;
mp.y = j;
mp.eType = TileType.Normal;
mp.iLayer = 0;
mp.iTileID = 0;
this.mapFile.lMap.Add(mp);
}
}
}
Found the problem
Alright, that was an issue on my side. Since I used
Canvas.SetTop(imgAdd, y * tileHeight);
I forgot that the values I previously used were the tile position, not the width. When setting a tile manually, it showed, as example, X: 1 Y: 2, whereas the loop showed X: 16 Y: 32. Seems like I'm missing my coffee today, haha.
You shouldnt be using margin to place items on a Canvas. You have to set position of the images using Canvas.SetTop and Canvas.SetLeft. I am guessing that all your images are added to the canvas but at the same location so that you only see one object at any given time.
See more about adding controls to canvas on MSDN
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.