2013-03-10 63 views
0

我正試圖在畫布上繪製一排矩形。當我運行下面的代碼時,即使我的畫布元素表示它有12個孩子,我也只能得到一個矩形。 尺寸是一個具有2個整數屬性(高度和寬度)的類。我正在繪製的畫布是400px x 600px。C在畫布上繪製多個矩形#

Dimensions windowDimensions = new Dimensions() 
     { 
      Width = (int)cvsGameWindow.Width, 
      Height = (int)cvsGameWindow.Height 
     }; 

     //init rectangles 
     for (int i = 0; i < windowDimensions.Width; i+=50) 
     { 
      Rectangle rect = new Rectangle(); //create the rectangle 
      rect.StrokeThickness = 1; //border to 1 stroke thick 
      rect.Stroke = _blackBrush; //border color to black 
      rect.Width = 50; 
      rect.Height = 50; 
      rect.Name = "box" + i.ToString(); 
      Canvas.SetLeft(rect,i * 50); 
      _rectangles.Add(rect); 
     } 
     foreach (var rect in _rectangles) 
     { 
      cvsGameWindow.Children.Add(rect); 
     } 

和私有成員宣佈在我的代碼的頂部:

private SolidColorBrush _blackBrush = new SolidColorBrush(Colors.Black); 
private SolidColorBrush _redBrush = new SolidColorBrush(Colors.Red); 
private SolidColorBrush _greenBrush = new SolidColorBrush(Colors.Green); 
private SolidColorBrush _blueBrush = new SolidColorBrush(Colors.Blue); 
private List<Rectangle> _rectangles = new List<Rectangle>(); 

回答

3

這是罪魁禍首:

Canvas.SetLeft(rect,i * 50); 

在第一循環中,與i=0,你設置Canvas.Left = 0;由於你的for循環正在做i+=50,所以在第二個循環中我將是50,所以你會設置Canvas.Left = 2500。你說你的Canvas400x600,所以你的矩形不在屏幕上。

最簡單的解決辦法:使用Canvas.SetLeft(rect, i) - 因爲i在50

+0

感謝的增量增加。而我怎麼沒有發現我不知道XD – 2013-03-10 18:08:45