操作說明:對 Visual 中的幾何進行點擊測試
此範例會示範如何在由一或多個 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 來進行點擊測試。 如果幾何是經過繪製,筆觸可延伸至填滿範圍外。 在該情況下,除了 FillContains 之外,您可能還會想呼叫 StrokeContains。
您也可以提供針對貝茲壓平合併目的所使用的 ToleranceType。
注意
這個範例不會將任何可能套用至幾何的轉換或裁剪列入考慮。 此外,這個範例無法搭配樣式化控制項運作,因為它不具備任何直接與其相關聯的圖案。