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