Posts Tagged ‘Contains’

workaround: Silverlight Rect class missing ‘bool Contains(Rect)’ method

In ClipFlair, I’ve been looking into porting Kael Rowan’s ZoomableCanvas (related to ZUI code used in Code Canvas, Debugger Canvas etc. VisualStudio add-ons) from WPF to Silverlight.

One of the issues I found was that Silverlight’s Rect class (I guess this is a case for .NET Compact Framework in general) doesn’t have a method to check if a Rect contains another Rect, as does the full .NET framework which is available in WPF. That method was needed in Kael’s PriorityQuadTree source code.

Since we can check whether a Rect is contained in another Rect by checking if both its top-left and top-right points are contained, I edited Kael’s RectExtensions class, adding the following method:

/// <summary>
/// Indicates whether the current rectangle contains the specified rectangle, 
/// by checking for containment of the specified rectangle's top-left and
/// bottom-right points.
/// </summary> /// <param name="self">The current rectangle.</param> /// <param name="rect">The rectangle to check.</param> /// <returns><c>true</c> if the current rectangle contains the specified
/// rectangle; otherwise, <c>false</c>.</returns> public static bool Contains(this Rect self, Rect rect){ return self.Contains(new Point(rect.Left, rect.Top))
&& self.Contains(new Point(rect.Right, rect.Bottom)); }

Note that RectExtensions is a static (with only static methods, not instantiatable) class containing static extension methods (a feature of recent .NET versions), for the Rect class. So, once you’ve imported the RectExtensions class in a Silverlight class (assuming you have RectExtensions in the same project or in some referenced Silverlight or Portable library), all Rect instances gain a new method “bool Contains(Rect)” apart from the “bool Contains(Point)” one.

BTW, speaking of Zoomable User Interfaces (ZUIs) above, an important difference between WPF and Silverlight is that WPF has a theoretically unboundeded coordinate system, in contrast to Silverlight’s bounded one, where the maximum value for a coordinate component is approximately +32768. As stated in Microsoft’s WPF Compatibility article:

WPF has a theoretically unbounded coordinate system. Silverlight has a bounded coordinate system. The maximum value for a coordinate component in Silverlight is approximately +32678. APIs that represent a Silverlight coordinate might throw a native-level error or raise an exception if this maximum value is exceeded. This is true even for values that might be temporary and not intended for the final rendering value. 32678 is well beyond the maximum screen size, so this should only be an issue if you are performing math or applying transforms to coordinate values.

%d bloggers like this: