Silverlight的HitTest

在开发RIA,我们经常在某一点的控件或者是在一个范围内的控件,在Silverlight3中提供了方法帮我们解决VisualTreeHelper.FindElementsInHostCoordinates 。

 

  名称 说明
FindElementsInHostCoordinates(Point, UIElement) 检索一组对象,这些对象位于某一对象的坐标空间的指定点内。
FindElementsInHostCoordinates(Rect, UIElement) 检索一组对象,这些对象位于某一对象的坐标空间的指定 Rect 内。

用法:

List<UIElement> list = VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(null), LayoutRoot as UIElement) as List<UIElement>;

2,他也可以运用于判断控件的重叠。

public bool CheckCollisionPoint(Point pt, FrameworkElement control, FrameworkElement controlElem) { if (controlElem is Image) { // NOTE that we saved the WB in the Tag object for performance. // in a real app, you might abstract this in your sprite class. WriteableBitmap wb = controlElem.Tag as WriteableBitmap; int width = wb.PixelWidth; int height = wb.PixelHeight; double offSetX = Convert.ToDouble(control.GetValue(Canvas.LeftProperty)); double offSetY = Convert.ToDouble(control.GetValue(Canvas.TopProperty)); pt.X = pt.X - offSetX; pt.Y = pt.Y - offSetY; int offset = Convert.ToInt32((width * pt.Y) + pt.X); return (wb.Pixels[offset] != 0); } else { List<UIElement> hits = System.Windows.Media.VisualTreeHelper.FindElementsInHostCoordinates(pt, controlElem) as List<UIElement>; return (hits.Contains(controlElem)); } }

private bool CheckCollision(FrameworkElement control1, FrameworkElement controlElem1, FrameworkElement control2, FrameworkElement controlElem2) { // first see if sprite rectangles collide Rect rect1 = UserControlBounds(control1); Rect rect2 = UserControlBounds(control2); rect1.Intersect(rect2); if (rect1 == Rect.Empty) { // no collision - GET OUT! return false; } else { bool bCollision = false; Point ptCheck = new Point(); // NOTE that creating the writeablebitmap is a bit intense // so we will do this once and store results in Tag property // in a real game, you might abstract this into a Sprite class. if (controlElem1 is Image) controlElem1.Tag = GetWriteableBitmap(control1); if (controlElem2 is Image) controlElem2.Tag = GetWriteableBitmap(control2); // now we do a more accurate pixel hit test for (int x = Convert.ToInt32(rect1.X); x < Convert.ToInt32(rect1.X + rect1.Width); x++) { for (int y = Convert.ToInt32(rect1.Y); y < Convert.ToInt32(rect1.Y + rect1.Height); y++) { ptCheck.X = x; ptCheck.Y = y; if (CheckCollisionPoint(ptCheck, control1, controlElem1)) if (CheckCollisionPoint(ptCheck, control2, controlElem2)) { bCollision = true; break; } } if (bCollision) break; } return bCollision; } }

 

详细见:http://blogs.microsoft.co.il/blogs/alex_golesh/archive/2009/08/11/silverlight-quick-tip-how-to-perform-a-hit-test.aspx

 

http://www.andybeaulieu.com/Home/tabid/67/EntryID/160/Default.aspx

 

代码下载

你可能感兴趣的:(image,object,list,null,silverlight,RIA)