我们可以使用RectangleGeometry来绘制一个矩形或者正方形

RectangleGeometry 类:描述二维矩形

下面我们先来看一段代码:

<Window x:Class="WPF.SimpleGraph.Rectangle"
        xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
        Title
="Rectangle" Height="300" Width="300">
    
<Canvas>
        
<Path Stroke="Red" StrokeThickness="5">
            
<Path.Data>
                
<RectangleGeometry Rect="50,50,150,80"></RectangleGeometry>
            
</Path.Data>
        
</Path>
    
</Canvas>
</Window>

执行结果:

其中RectangleGeometry 表示一个矩形图形,Rect表示矩形的尺寸,它用一个数值字符串表示,数值之间使用逗号分割,例如"50,50,150,80",假设参数"x=50,y=50,w=150,h=80"前面两位x,y表示该矩形左上端点的位置,如果设置x=0,y=0便于canvas边框重叠,w表示width矩形的宽度,h表示height矩形的高度。

 

同理,如果我们想要定义一个正方形,可以使w=h即可

<RectangleGeometry Rect="0,0,120,120"></RectangleGeometry>

结果: