C# 如何在 WPF 画布上绘制矩形
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14782158/
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 on a WPF canvas
提问by Sheena
I'm trying to draw a Rectangle
on a Canvas
as follows:
我想画Rectangle
上一个Canvas
如下:
System.Windows.Shapes.Rectangle rect;
rect = new System.Windows.Shapes.Rectangle();
rect.Stroke = new SolidColorBrush(Colors.Black);
rect.Fill = new SolidColorBrush(Colors.Black);
rect.Width=200;
rect.Height=200;
Canvas.SetLeft(rect,0);
Canvas.SetTop(rect,0);
front_canvas.Children.Add(rect);
Why would this code not draw a rectangle?
为什么这段代码不绘制矩形?
The canvas is defined in the associated XAML as follows:
画布在关联的 XAML 中定义如下:
<Canvas Height="200" Width="200" Name="front_canvas" Grid.Row="1" Grid.Column="0">
</Canvas>
The canvas shows up fine. I can tell because of the gap it leaves in the layout grid.
画布显示良好。我可以分辨出它在布局网格中留下的间隙。
采纳答案by Reed Copsey
This should draw your rectangle as a 200x200 black square, provided front_canvas
is displayed correctly.
如果front_canvas
显示正确,这应该将您的矩形绘制为 200x200 的黑色正方形。
Why would this code not draw a rectangle?
为什么这段代码不绘制矩形?
The main reasons this would not draw are:
这不会绘制的主要原因是:
front_canvas
is not visiblefront_canvas
is not in the visual tree and being displayed correctly- Some other
FrameworkElement
is obscuringfront_canvas
, at least the upper left corner. - There is another object in the canvas at a higher z order.
front_canvas
不可见front_canvas
不在可视化树中并正确显示- 其他一些
FrameworkElement
是模糊的front_canvas
,至少是左上角。 - 画布中还有一个更高 z 阶的对象。
Note that you'd typically also want to set StrokeThickness
if you want to see the Stroke
you specify.
请注意,StrokeThickness
如果您想查看Stroke
您指定的内容,您通常还需要设置。
回答by SHEKHAR SHETE
To View Rectangle you must specify the StrokeThickness
and set any Integer
value greater than zero:
要查看矩形,您必须指定StrokeThickness
并设置任何Integer
大于零的值:
rect.StrokeThickness=2;