我正试图在我的画布上画一排长方形。当我运行以下代码时,我只得到一个矩形,即使我的canvas元素说它有12个子元素。 Dimensions是一个具有2个整数属性的类,Height和Width。我绘制的画布是400px乘600px。
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>();
答案 0 :(得分:3)
这是罪魁祸首:
Canvas.SetLeft(rect,i * 50);
在第一个循环中,使用i=0
,您正在设置Canvas.Left = 0
;由于您的for循环正在i+=50
,因此在第二个循环中我将50
,因此您将设置Canvas.Left = 2500
。您说Canvas
为400x600
,因此您的矩形在屏幕外。
最简单的解决方法:使用Canvas.SetLeft(rect, i)
- 因为i
以50为增量增加。