在Silverlight中,Size、Rect、Rectangle、RectangleGeometry有点相像,有点关联,零星散落用到一个是一个,不如放在一块比较比较,联系联系,加深理解。
Size其实是个结构体,只有一个构造函数,需要两个参数,描述对象的高度和宽度。示意如下:
public struct Size
{
public Size(double width, double height)
{
if ((width < 0.0) || (height < 0.0))
{
throw new ArgumentException();
}
this._width = width;
this._height = height;
}
}
尽管宽和高是double,但尽量还应使用整数值。(PS:用double是为了和WPF兼容,此乃后话。)同时宽和高不能为负值,上限不是double.PositiveInfinity,而是一个由Silverlight本机的代码强制实施的较低数字,约为1,000,000.
Rect和Size非常类似,也是结构体,但除了宽高之外,Rect还指定了原点(X,Y)。一般Rect用于与较低级别的图形表现相关的API,而Size用于与UI表现和布局相关的API。有三个构造函数,示意如下:
public struct Rect
{
public Rect(double x, double y, double width, double height)
{
if (width < 0.0)
{
throw new ArgumentException("", "width");
}
if (height < 0.0)
{
throw new ArgumentException("", "height");
}
this._x = x;
this._y = y;
this._width = width;
this._height = height;
}
public Rect(Point point1, Point point2);
public Rect(Point location, Size size);
}
宽高情况与Size类似,(即不可以为负值,帮助文档中宽高可以为负值是错误的。)原点可以为负值,表示起点在布局之外。
可见Rect本质就是一个值,这个值是个矩形区域。由于命名原因,常与Rectangle相混淆,其实这两兄弟基本就没联系。Rectangle是一个UI元素,隶属于Shape,仍在XAML中,出来的就是个矩形,还可以对这个矩形Shape填充颜色、增加事件等。代码示意:
public sealed class Rectangle : Shape { }
Rect、Rectangle哥俩还有一个胞弟叫RectangleGeometry,看名字就知道它与Rectangle的区别就在于Geometry和Shape的差异:Shape类有Fill、Stroke、Opacity等呈现属性,而Geometry类只能定义几何图形,无法呈现。Geometry最常用于两个用途:1,作为Path形状的Data属性,用来描绘内容。2,用于Clip其他UI元素。
而RectangleGeometry有一个名字为Rect的属性,改属性的类型为Rect结构体。示意如下:
public sealed class RectangleGeometry : Geometry
{
public Rect Rect { get; set; }
}
总结一下:
Size和Rect,都是结构体,宽高定义类似,但后者多个原点定义。
Rect和Rectangle,除了名字类似外,几乎不会用到一块。
Rect和RectangleGeometry,Rect作为一个值,可以赋给RectangleGeometry的Rect属性。
Rectangle和RectangleGeometry,两个都是密封类,由于继承自不同的父类Shape和Geometry,差异也一并显现。
![](https://i-blog.csdnimg.cn/blog_migrate/0f26ad4d8934e6baf1538f33e26a0acd.jpeg)
示例Rect和RectangleGeometry,有图片元素正常如左,被一RectangleGeometry剪辑,结果如右,示例代码:
img.Clip = new RectangleGeometry { Rect = new Rect(40, 20, 100, 100)};