HOW TO:對 Visual 中的幾何進行點擊測試
更新:2007 年 11 月
本範例示範如何在由一個或多個 Geometry 物件組成的視覺物件上執行點擊測試 (Hit Test)。
範例
下列範例示範如何從使用 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.
}
}
}
}
FillContains 方法是一種多載方法,可以讓您使用指定的 Point 或 Geometry 進行點擊測試。如果為幾何圖案描邊,描邊部分可能會超出填色週框。在這種情況下,除了 FillContains 之外,您可能還需要呼叫 StrokeContains。
您也可以提供 ToleranceType,以達到貝茲簡維化的目的。
![]() |
---|
這個範例並未考慮幾何圖案上可能套用的任何轉換或裁剪設定。此外,此範例也不會使用樣式控制項,因為它沒有任何與其直接關聯的繪圖。 |