2014-07-16 44 views
0

我目前正在使用畫布進行繪製的WPF平鋪地圖編輯器,但由於某種原因,它不適用於循環。WPF畫布不會在循環中正確繪製

我已經生成了基於16x16拼貼的160px160p地圖。 當我嘗試將它們添加到循環中時,它不會添加它們。

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

在使用中,我創建應該包含所有我想要添加的瓷磚文本框,並且確實如此,但由於某種原因在畫布上保持爲空(或只增加1-4瓦,依賴於畫布的尺寸)。 click for example

當試圖手動添加它們(MouseEvent)它工作正常,只有循環導致問題。 爲什麼?

編輯: 改變了保證金機頂盒& SetLeft,添加功能生成地圖

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

發現問題

好吧,那是在我這邊的問題。 由於我用

Canvas.SetTop(imgAdd, y * tileHeight); 

我忘了,我先前使用的值是瓦片位置,而不是寬度。 手動設置瓷磚時,例如顯示X:1 Y:2,而循環顯示X:16 Y:32.好像我今天錯過了我的咖啡,哈哈。

回答

1

您不應該使用邊距將項目放置在畫布上。您必須使用Canvas.SetTop和Canvas.SetLeft設置圖像的位置。我猜測你所有的圖像都被添加到畫布上,但是在同一個位置,所以你只能在任何給定的時間看到一個對象。

查看更多關於MSDN

+0

將控件添加到畫布上我使用機頂盒和SetLeft但不幸的是這個問題仍然改變它。感謝提供保證金和SetTop/SetLeft的提示,因爲保證金正常工作,所以我不打擾它。 – Xijezu

+0

在您提供的圖像中(我猜測是日誌文件),您的x和y值爲0?是對的嗎?索引總是0?你可以發佈新的代碼,你設置圖像的頂部和左側? – Krishna

+0

瓦片保持不變(考慮爲每個瓦片使用不同的瓦片,但結果相同),x和y由一個類生成。我添加了新的功能和生成地圖的功能 – Xijezu