简体   繁体   English

如何在WPF中绘制带有背景色的矩形

[英]How to draw a rectangle with a background color in WPF

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.请帮忙。

You can use您可以使用

Canvas.SetLeft(rect, <offset>) Canvas.SetRight(...), Canvas.SetTop(...), Canvas.SetBottom(...)

to position UIElement in the Canvas container.在 Canvas 容器中定位 UIElement。

Use Random class to generate the xy co-ordinates使用 Random 类生成 xy 坐标

Random r=new Random();
r.Next(1,100);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM