此示例演示如何对由一个或多个 Geometry 对象组成的视觉对象执行命中测试。
示例:
以下示例演示如何从使用该GetDrawing方法的视觉对象中检索DrawingGroup该对象。 然后,对DrawingGroup中每个绘图的呈现内容执行命中测试,以确定其中哪个几何图形被命中。
注释
在大多数情况下,你将使用 HitTest 该方法来确定某个点是否与视觉对象的任何呈现内容相交。
// Determine if a geometry within the visual was hit.
static public void HitTestGeometryInVisual(Visual visual, Point pt)
{
// Retrieve the group of drawings for the visual.
DrawingGroup drawingGroup = VisualTreeHelper.GetDrawing(visual);
EnumDrawingGroup(drawingGroup, pt);
}
// Enumerate the drawings in the DrawingGroup.
static public void EnumDrawingGroup(DrawingGroup drawingGroup, Point pt)
{
DrawingCollection drawingCollection = drawingGroup.Children;
// Enumerate the drawings in the DrawingCollection.
foreach (Drawing drawing in drawingCollection)
{
// If the drawing is a DrawingGroup, call the function recursively.
if (drawing.GetType() == typeof(DrawingGroup))
{
EnumDrawingGroup((DrawingGroup)drawing, pt);
}
else if (drawing.GetType() == typeof(GeometryDrawing))
{
// Determine whether the hit test point falls within the geometry.
if (((GeometryDrawing)drawing).Geometry.FillContains(pt))
{
// Perform action based on hit test on geometry.
}
}
}
}
' Determine if a geometry within the visual was hit.
Public Shared Sub HitTestGeometryInVisual(ByVal visual As Visual, ByVal pt As Point)
' Retrieve the group of drawings for the visual.
Dim drawingGroup As DrawingGroup = VisualTreeHelper.GetDrawing(visual)
EnumDrawingGroup(drawingGroup, pt)
End Sub
' Enumerate the drawings in the DrawingGroup.
Public Shared Sub EnumDrawingGroup(ByVal drawingGroup As DrawingGroup, ByVal pt As Point)
Dim drawingCollection As DrawingCollection = drawingGroup.Children
' Enumerate the drawings in the DrawingCollection.
For Each drawing As Drawing In drawingCollection
' If the drawing is a DrawingGroup, call the function recursively.
If drawing.GetType() Is GetType(DrawingGroup) Then
EnumDrawingGroup(CType(drawing, DrawingGroup), pt)
ElseIf drawing.GetType() Is GetType(GeometryDrawing) Then
' Determine whether the hit test point falls within the geometry.
If (CType(drawing, GeometryDrawing)).Geometry.FillContains(pt) Then
' Perform action based on hit test on geometry.
End If
End If
Next drawing
End Sub
该方法 FillContains 是一种重载方法,允许你使用指定 Point 或 Geometry命中测试。 如果一个几何图形被描边,描边可以超出填充边界。 在这种情况下,你可能想要调用 StrokeContains 以及 FillContains。
还可以提供用于贝塞尔平展目的的一个 ToleranceType 。
注释
此示例不考虑可能应用于几何图形的任何转换或剪辑。 此外,此示例将不适用于带样式的控件,因为它没有任何直接与之关联的绘图。