操作說明:對 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 來點擊測試。 如果幾何是經過繪製,筆觸可延伸至填滿範圍外。 在此情況下,除了 之外,您可能想要呼叫 StrokeContainsFillContains 。
您也可以提供 ToleranceType 用於貝塞爾扁平化用途的 。
注意
這個範例不會將任何可能套用至幾何的轉換或裁剪列入考慮。 此外,這個範例無法搭配樣式化控制項運作,因為它不具備任何直接與其相關聯的圖案。