wpf 如何在WPF中绘制带有背景色的矩形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18560439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to draw a rectangle with a background color in WPF
提问by Debhere
Hi I want to have a rectangle like the below picture to fill the entire canvas with different sizes and at different position scatter through out the canvas. My solution environment is WPF C#
嗨,我想要一个像下图这样的矩形来填充整个画布,使其具有不同的大小和不同的位置,分散在画布中。我的解决环境是WPF C#


Could some one please guide me of how to do it? Till now what I have done is canvas_loaded
有人可以指导我如何做吗?到目前为止我所做的是 canvas_loaded
Rectangle rect = new Rectangle();
rect.Fill = new SolidColorBrush(Colors.Black);
rect.Width = 100;
rect.Height = 100;
rect.Stroke = new SolidColorBrush(Colors.Black);
But the problem here how will I position it to the different locaion of the canvas, the size and width I can provide at run time with different value but I need to position the rectangles (Square) at diffrent XY co-ordinates so that none of the rectangles or Squares overlapp each other.
但是这里的问题是我将如何将它定位到画布的不同位置,我可以在运行时提供不同值的大小和宽度,但我需要将矩形(方形)定位在不同的 XY 坐标处,以便没有矩形或正方形相互重叠。
Please help.
请帮忙。
回答by vitaliy zadorozhnyy
You can use
您可以使用
Canvas.SetLeft(rect, <offset>) Canvas.SetRight(...), Canvas.SetTop(...), Canvas.SetBottom(...)
to position UIElement in the Canvas container.
在 Canvas 容器中定位 UIElement。
回答by Nithin Nayagam
Use Random class to generate the xy co-ordinates
使用 Random 类生成 xy 坐标
Random r=new Random();
r.Next(1,100);

