前面幾章介紹了處理適量適中的圖形內容的最佳方法,通過使用幾何圖形、圖畫和路徑,可以降低2D圖形的開銷,即使正在使用復雜的具有分層效果的組合形狀和漸變畫刷,這種方法也仍然能夠正常得很好,
然而,這樣設計不適合需要渲染大量圖形元素的繪圖密集型應用程式,例如繪圖程式、演示粒子碰撞的物理模型程式或橫向卷軸形式的游戲,這些應用程式面臨的不是圖形復雜程度的問題,而純粹是單獨的圖形元素數量的問題,即使使用量級更輕的Geometry物件代替Path元素,需要的開銷也仍會較大地影回應用程式的性能,
WPF針對此類問題的解決方案是,使用低級的可視化層(visual layer)模型,基本思想是將每個圖形元素定義為一個Visual物件,Visual物件是極輕易級的要素,比Geometry物件或Path物件需要的開銷小,然后可使用單個元素在視窗中渲染所有可視化物件,
一、繪制可視化物件
Visual類是抽象類,所以不能創建該類的實體,相反,需要使用繼承自Visual類的某個類,包括UIElement類(該類是WPF元素模型的根)、Viewport3DVisual類(通過該類可顯示3D內容)以及ContainerVisual類(包含其他可視化物件的基本容器),但最有用的派生類是DrawingVisual類,該類繼承自ContainerVisual,并添加了支持“繪制”希望放置到可視化物件中的圖形內容的功能,
為使用DrawingVisual類繪制內容,需要呼叫DrawingVisual.RederOpen()方法,該方法回傳一個可用于定義可視化內容的DrawingContext物件,繪制完畢后,需要呼叫DrawingContext.Close()方法,下面是繪制圖形的完整程序:
DrawingVisual visual=new DrawingVisual(); DrawingContext dc=visual.RenderOpen(); //(perform drawing here.) dc.Close();
在本質上,DrawingContext類由各種為可視化物件增加了一些圖形細節的方法構成,可呼叫這些方法來繪制各種圖形、應用變換以及改變不透明度等,下表列出了DrawingContext類的方法,

下面的示例創建了一個可視化物件,該可視化物件包含沒有填充的基本的黑色三角形:
DrawingVisual visual=new DrawingVisual(); using(DrawingContext dc=visual.RenderOpen()) { Pen drawingPen=new Pen(Color.Black,3); dc.DrawLine(drawingPen,new Point(0,50),new Point(50,0)); dc.DrawLine(drawingPen,new Point(50,0),new Point(100,50)); dc.DrawLine(drawingPen,new Point(0,50),new Point(100,50)); }
當呼叫DrawingContext方法,沒有實際繪制可視化物件——而只是定義了可視化外觀,當通過呼叫Close()方法結束繪制時,完成的圖畫被存盤在可視化物件中,并通過只讀的DrawingVisual.Drawing屬性提供這些圖畫,WPF會保存Drawing物件,從而當需要時可以重新繪制視窗,
繪圖代碼的順序很重要,后面的繪圖操作可在已經存在的圖形上繪制內容,PushXxx()方法應用的設定會被應用到后續的繪圖操作中,例如,可使用PushOpacity()方法改變不透明級別,該設定會影響所有的后續繪圖操作,可使用Pop()方法恢復最佳的PushXxx()方法,如果多次呼叫PushXxx()方法,可一次使用一系列Pop()方法呼叫關閉它們,
一旦關閉DrawingContext物件,就不能再修改可視化物件,但可以使用DrawingVisual類的Transform和Opacity屬性應用變換或改變整個可視化物件的透明度,如果希望提供全新的內容,可以再次呼叫RenderOpen()方法并重復繪制程序,
二、在元素中封裝可視化物件
在可視化層中撰寫程式時,最重要的一步是定義可視化物件,但為了在螢屏上實際顯示可視內容,這還不夠,為顯示可視化物件,還需要借助于功能完備的WPF元素,WPF元素將可視化物件添加到可視化樹中,乍一看,這好像降低了可視化層變成的優點——畢竟,避免使用元素并避免它們的巨大開銷不正是使用可視化層的全部目的嗎?然而,單個元素具有顯示任意數量可視化物件的能力,因此,可以很容易地創建只包含一兩個元素,但卻駐留了幾千個可視化物件的視窗,
為在元素中駐留可視化物件,需要執行一下任務:
- 為元素呼叫AddVisualChild()和AddLogicalChild()方法來注冊可視化物件,從技術角度看,為了顯示可視化物件,不需要執行這些任務,但為了確保正確跟蹤可視化物件,在可視化樹和邏輯樹中顯示可視化物件以及使用其他WPF特性(如命中測驗),需要執行這些操作,
- 重寫VisualChildrenCount屬性并回傳已經增加了的可視化物件的數量,
- 重寫GetVisualChild()方法,當通過索引好要求可視化物件時,添加回傳可視化物件所需的代碼,
當重寫VisualChildrenCount屬性和GetVisualChild()方法時,本質上時劫持了那個元素,如果使用的是能夠包含嵌套的內容控制元件、裝飾元素或面板,這些元素將不再被渲染,例如,如果在自定義視窗中重寫了這兩個方法,就看不到視窗的其他內容,只會看到添加的可視化物件,
因此,通常創建專用的自定義類來封裝希望顯示的可視化物件,例如,分析下圖顯示的視窗,該視窗允許用戶為自定義的Canvas面板添加正方形(每個正方形是可視化物件).

在上圖中,視窗的左邊是具有三個RadioButton物件的工具列,通過使用一組RadioButton物件,科室創建一套相互關聯的按鈕,當單擊這套按鈕中的某個按鈕時,該按鈕會被選中,并保持“按下”狀態,而原來選擇的按鈕會恢復成正常的外觀,
在上圖中,視窗的右邊為自定義的名為DrawingCanvas的Canvas面板,該面板在內部存盤了可視化物件的集合,DrawingCanvas面板回傳保存在VisualChildrenCount屬性的正方形總數量,并使用GetVisualChild()方法提供對集合中每個可視化物件的訪問,下面是實作細節:
public class DrawingCanvas:Panel { private List<Visual> visuals = new List<Visual>(); protected override Visual GetVisualChild(int index) { return visuals[index]; } protected override int VisualChildrenCount { get { return visuals.Count; } } ... }
此外,DrawingCanvas類還提供了AddVisual()方法和DeleteVisual()方法,以簡化在集合的恰當位置插入可視化物件的自定義代碼:
public void AddVisual(Visual visual) { visuals.Add(visual); base.AddVisualChild(visual); base.AddLogicalChild(visual); } public void DeleteVisual(Visual visual) { visuals.Remove(visual); base.RemoveVisualChild(visual); base.RemoveLogicalChild(visual); }
DrawingCanvas類沒有提供用于繪制、選擇以及移動正方形的邏輯,這是因為該功能是在應用程式層中控制的,因為可能有幾個不同的繪圖工具都使用同一個DrawingCanvas類,所以這樣做是合理的,根據用戶單擊的按鈕,用戶可繪制不同型別的形狀,或使用不同的筆畫顏色和填充顏色,所有這些細節都是特定與視窗的,DrawingCanvas類提供了用于駐留、渲染以及跟蹤可視化物件的功能,
下面演示了如何在視窗的XAML標記中宣告DrawingCanvas物件:
<local:DrawingCanvas x:Name="drawingSurface" Background="White" ClipToBounds="True" MouseLeftButtonDown="drawingSurface_MouseLeftButtonDown" MouseLeftButtonUp="drawingSurface_MouseLeftButtonUp" MouseMove="drawingSurface_MouseMove"></local:DrawingCanvas>
上圖已經分析了DrawingCanvas容器,現在應當分析創建正方形的事件處理代碼了,首先分析MouseLeftButton事件的處理程式,正是該事件處理程式中的代碼決定了將要執行什么操作——是創建正方形、洗掉正方形還是選擇正方形,目前,我們只對第一個任務感興趣:
private void drawingSurface_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Point pointClicked = e.GetPosition(drawingSurface); if (cmdAdd.IsChecked == true) { DrawingVisual visual = new DrawingVisual(); DrawSquare(visual, pointClicked, false); drawingSurface.AddVisual(visual); } ... }
實際作業由自定義的DrawSquare()方法執行,該方法非常有用,因為需要在代碼中的幾個不同位置觸發正方形繪制操作,顯然,當第一次創建正方形時,需要使用DrawSquare()方法,當正方形的外觀因為各種原因發生變化時(例如,當正方形被選中時),也需要使用該方法,
DrawSquare()方法接收三個引數:準備繪制的DrawingVisual物件、正方形左上角的點以及知識當前是否選中正方形的Boolean標志,對于選中的正方形使用不同的填充顏色進行填充,
下面是渲染代碼:
// Drawing constants. private Brush drawingBrush = Brushes.AliceBlue; private Brush selectedDrawingBrush = Brushes.LightGoldenrodYellow; private Pen drawingPen = new Pen(Brushes.SteelBlue, 3); private Size squareSize = new Size(30, 30); private DrawingVisual selectionSquare; // Rendering the square. private void DrawSquare(DrawingVisual visual, Point topLeftCorner, bool isSelected) { using (DrawingContext dc = visual.RenderOpen()) { Brush brush = drawingBrush; if (isSelected) brush = selectedDrawingBrush; dc.DrawRectangle(brush, drawingPen, new Rect(topLeftCorner, squareSize)); } }
這就是在視窗中顯示可視化物件需要做的全部作業:渲染可視化物件的代碼,以及處理必需的跟蹤細節的內容,如果希望為可視化物件添加互動功能,還需要完成其他一些作業,
三、命中測驗
繪制正方形的應用程式不僅允許繪制正方形,還允許用戶移動和洗掉以及繪制的正方形,為了執行這些任務,需要撰寫代碼以截獲滑鼠單擊,并查找位于可單擊位置的可視化物件,該任務被稱為命中測驗(hit testing),
為支持命中測驗,最好為DrawingCanvas類添加GetVisual()方法,該方法使用一個點作為引數并回傳匹配的DrawingVisual物件,為此使用了VisualTreeHelper.HitTest()靜態方法,下面是GetVisual()方法的完整帶代碼:
public DrawingVisual GetVisual(Point point) { HitTestResult hitResult = VisualTreeHelper.HitTest(this, point); return hitResult.VisualHit as DrawingVisual; }
在該例中,代碼忽略了所有非DrawingVisual型別的命中物件,包括DrawingCanvas物件本身,如果沒有正方形被單擊,GetVisual()方法回傳null參考,
洗掉功能利用了GetVisual()方法,當選擇洗掉命令并選中一個正方形時,MouseLeftButtonDown事件處理程式使用下面的代碼洗掉這個正方形:
else if (cmdDelete.IsChecked == true) { DrawingVisual visual = drawingSurface.GetVisual(pointClicked); if (visual != null) drawingSurface.DeleteVisual(visual); }
可用類似的代碼支持拖放特性,但需要通過一種方法對拖動進行跟蹤,在視窗中添加了三個欄位用于該目的——isDragging、clickOffset和selectedVisual:
// Variables for dragging shapes. private bool isDragging = false; private Vector clickOffset; private DrawingVisual selectedVisual;
當用戶單擊某個形狀時,isDragging欄位被設定為true,selectedVisual欄位被設定為被單擊的可視化物件,而clickOffset欄位記錄了用戶單擊點和正方形左上角之間的距離,下面是MouseLeftButtonDown事件處理程式中的相關代碼:
else if (cmdSelectMove.IsChecked == true) { DrawingVisual visual = drawingSurface.GetVisual(pointClicked); if (visual != null) { // Calculate the top-left corner of the square. // This is done by looking at the current bounds and // removing half the border (pen thickness). // An alternate solution would be to store the top-left // point of every visual in a collection in the // DrawingCanvas, and provide this point when hit testing. Point topLeftCorner = new Point( visual.ContentBounds.TopLeft.X + drawingPen.Thickness / 2, visual.ContentBounds.TopLeft.Y + drawingPen.Thickness / 2); DrawSquare(visual, topLeftCorner, true); clickOffset = topLeftCorner - pointClicked; isDragging = true; if (selectedVisual != null && selectedVisual != visual) { // The selection has changed. Clear the previous selection. ClearSelection(); } selectedVisual = visual; }
除基本的記錄資訊外,上面的代碼還呼叫DrawSquare()方法,使用新顏色重新渲染DrawingVisual物件,上面的代碼還使用另一個自定義方法ClearSelection(),該方法重新繪制以前選中的正方形,使該正方形恢復其正常外觀:
private void ClearSelection() { Point topLeftCorner = new Point( selectedVisual.ContentBounds.TopLeft.X + drawingPen.Thickness / 2, selectedVisual.ContentBounds.TopLeft.Y + drawingPen.Thickness / 2); DrawSquare(selectedVisual, topLeftCorner, false); selectedVisual = null; }
接下來,當用戶拖動時需要實際移動正方形,并當用戶釋放滑鼠左鍵時結束拖動操作,這兩個任務是使用一些簡單的事件處理代碼完成的:
private void drawingSurface_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { isDragging = false; } private void drawingSurface_MouseMove(object sender, MouseEventArgs e) { if (isDragging) { Point pointDragged = e.GetPosition(drawingSurface) + clickOffset; DrawSquare(selectedVisual, pointDragged, true); } }
四、復雜的命中測驗
在上面的示例中,命中測驗代碼始侄訓傳最上面的可視化物件(如果單擊空白處,就回傳null參考),然而,VisualTreeHelper類提供了HitTest()方法的兩個多載版本,從而可以執行更加復雜的命中測驗,使用這些方法,可以檢索位于特定點的所有可視化物件,即使它們被其他元素隱藏在后面也同樣如此,還可找到位于給定幾何圖形中的所有可視化物件,
為了使用這個更高級的命中測驗行為,需要創建回呼函式,之后,VisualTreeHelper類自上而下遍歷所有可視化物件(與創建它們的順序相反),每當發現匹配的物件時,就會呼叫回呼函式并傳遞相關細節,然后可以選擇停止查找(如果已經查找到足夠的層次),或繼續查找知道遍歷完所有的可視化物件為止,
下面的代碼通過為DrawingCanvas類添加GetVisuals()方法實作了該技術,GetVisuals()方法接收一個Geometry物件,該物件用于命中測驗,GetVisuals()方法創建回呼函式委托、清空命中測驗結果的集合,然后通過呼叫VisualTreeHelper.HitTest()方法啟動命中測驗程序,當該程序結束時,該方法回傳包含所有找到的可視化物件的集合:
private List<DrawingVisual> hits = new List<DrawingVisual>(); public List<DrawingVisual> GetVisuals(Geometry region) { hits.Clear(); GeometryHitTestParameters parameters = new GeometryHitTestParameters(region); HitTestResultCallback callback = new HitTestResultCallback(this.HitTestCallback); VisualTreeHelper.HitTest(this, null, callback, parameters); return hits; }
回呼方法實作了命中測驗行為,通常,HitTestResult物件只提供一個熟悉(VisualHit),但可以根據執行命中測驗的型別,將它轉換成兩個派生型別中的任意一個,
如果使用一個點進行命中測驗,可將HitTestResult物件轉換為PointHitTestResult物件,該類提供了一個不起眼的PointHit熟悉,該屬性回傳用于執行命中測驗的原始點,但如果使用Geometry物件吉祥鳥命中測驗,如本例那樣,可將HitTestResult物件轉換為GeometryHitTestResult物件,并訪問IntersectionDetail屬性,IntersectionDetail屬性告知幾何圖形是否完全封裝了可視化物件(FullyInside),幾何圖形是否與可視化元素只是相互重疊(Intersets),或者用于命中測驗的集合圖形是否落在可視化元素的內部(FullyContains),在該例中,只有當可視化物件完全位于命中測驗區域時,才會對命中數量計算,最后,在回呼函式的末尾,可回傳兩個HitTestResultBehavior列舉值中的一個:回傳continue表示繼續查找命中,回傳Stop則表示結束查找程序,
private HitTestResultBehavior HitTestCallback(HitTestResult result) { GeometryHitTestResult geometryResult = (GeometryHitTestResult)result; DrawingVisual visual = result.VisualHit as DrawingVisual; if (visual != null && geometryResult.IntersectionDetail == IntersectionDetail.FullyInside) { hits.Add(visual); } return HitTestResultBehavior.Continue; }
使用GetVisuals()方法,可創建如下圖所示的復雜選擇框效果,在此,用戶在一組矩形的周圍繪制了一個方框,應用程式接著報告該區域中矩形的數量,

為了創建選擇框,視窗只需要為DrawingCanvas面板添加另一個DrawingVisual物件即可,在視窗中還作為成員欄位存盤了指向選擇框的參考,此外還有isMultiSelecting標記和selectionSquareTopLeft欄位,當繪制選擇框時,isMultiSelecting標記跟蹤正在進行的選擇操作,selectionSquareTopLeft欄位跟蹤當前選擇框的左上角:
// Variables for drawing the selection square. private bool isMultiSelecting = false; private Point selectionSquareTopLeft;
為實作選擇框特性,需要為前面介紹的事件處理程式添加一些代碼,當單擊滑鼠時,需要創建選擇框,將isMultiSelecting開關設定為true,并捕獲滑鼠,下面的MouseLeftButtonDown事件處理程式中的代碼完成這項作業:
else if (cmdSelectMultiple.IsChecked == true) { selectionSquare = new DrawingVisual(); drawingSurface.AddVisual(selectionSquare); selectionSquareTopLeft = pointClicked; isMultiSelecting = true; // Make sure we get the MouseLeftButtonUp event even if the user // moves off the Canvas. Otherwise, two selection squares could be drawn at once. drawingSurface.CaptureMouse(); }
現在,當移動滑鼠時,可根據當前選擇框是否處于激活狀態,如果是激活狀態,就繪制它,為此,需要在MouseMove事件處理程式中添加以下代碼:
else if (isMultiSelecting) { Point pointDragged = e.GetPosition(drawingSurface); DrawSelectionSquare(selectionSquareTopLeft, pointDragged); }
實際的繪圖操作在專門的DrawSelectionSquare()方法中進行,該方法與前面介紹的DrawSquare()方法有一些類似之處:
private Brush selectionSquareBrush = Brushes.Transparent; private Pen selectionSquarePen = new Pen(Brushes.Black, 2); private void DrawSelectionSquare(Point point1, Point point2) { selectionSquarePen.DashStyle = DashStyles.Dash; using (DrawingContext dc = selectionSquare.RenderOpen()) { dc.DrawRectangle(selectionSquareBrush, selectionSquarePen, new Rect(point1, point2)); } }
最后,當釋放滑鼠時,可執行命中測驗,顯示訊息框,然后移除選擇框,為此,需要MouseLeftButtonUp事件處理程式中添加如下代碼:
if (isMultiSelecting) { // Display all the squares in this region. RectangleGeometry geometry = new RectangleGeometry( new Rect(selectionSquareTopLeft, e.GetPosition(drawingSurface))); List<DrawingVisual> visualsInRegion = drawingSurface.GetVisuals(geometry); MessageBox.Show(String.Format("You selected {0} square(s).", visualsInRegion.Count)); isMultiSelecting = false; drawingSurface.DeleteVisual(selectionSquare); drawingSurface.ReleaseMouseCapture(); }
本實體的完整代碼如下所示:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media; namespace Drawing { public class DrawingCanvas:Panel { private List<Visual> visuals = new List<Visual>(); protected override Visual GetVisualChild(int index) { return visuals[index]; } protected override int VisualChildrenCount { get { return visuals.Count; } } public void AddVisual(Visual visual) { visuals.Add(visual); base.AddVisualChild(visual); base.AddLogicalChild(visual); } public void DeleteVisual(Visual visual) { visuals.Remove(visual); base.RemoveVisualChild(visual); base.RemoveLogicalChild(visual); } public DrawingVisual GetVisual(Point point) { HitTestResult hitResult = VisualTreeHelper.HitTest(this, point); return hitResult.VisualHit as DrawingVisual; } private List<DrawingVisual> hits = new List<DrawingVisual>(); public List<DrawingVisual> GetVisuals(Geometry region) { hits.Clear(); GeometryHitTestParameters parameters = new GeometryHitTestParameters(region); HitTestResultCallback callback = new HitTestResultCallback(this.HitTestCallback); VisualTreeHelper.HitTest(this, null, callback, parameters); return hits; } private HitTestResultBehavior HitTestCallback(HitTestResult result) { GeometryHitTestResult geometryResult = (GeometryHitTestResult)result; DrawingVisual visual = result.VisualHit as DrawingVisual; if (visual != null && geometryResult.IntersectionDetail == IntersectionDetail.FullyInside) { hits.Add(visual); } return HitTestResultBehavior.Continue; } } }DrawingCanvas
<Window x:Class="Drawing.VisualLayer" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:Drawing" Title="VisualLayer" Height="300" Width="394.737"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"></ColumnDefinition> <ColumnDefinition></ColumnDefinition> </Grid.ColumnDefinitions> <ToolBarTray Orientation="Vertical"> <ToolBar> <RadioButton Margin="0,3" Name="cmdSelectMove"> <StackPanel> <Image Source="pointer.png" Width="35" Height="35"></Image> <TextBlock>Select/Move</TextBlock> </StackPanel> </RadioButton> <RadioButton Margin="0,3" IsChecked="True" Name="cmdAdd"> <StackPanel> <Rectangle Width="30" Height="30" Stroke="SteelBlue" StrokeThickness="3" Fill="AliceBlue"></Rectangle> <TextBlock>Add Square</TextBlock> </StackPanel> </RadioButton> <RadioButton Margin="0,3" Name="cmdDelete"> <StackPanel> <Path Stroke="SteelBlue" StrokeThickness="4" StrokeEndLineCap="Round" StrokeStartLineCap="Round" Fill="Red" HorizontalAlignment="Center"> <Path.Data> <GeometryGroup> <PathGeometry> <PathFigure StartPoint="0,0"> <LineSegment Point="18,18"></LineSegment> </PathFigure> <PathFigure StartPoint="0,18"> <LineSegment Point="18,0"></LineSegment> </PathFigure> </PathGeometry> </GeometryGroup> </Path.Data> </Path> <TextBlock>Delete Square</TextBlock> </StackPanel> </RadioButton> <RadioButton Margin="0,3" Name="cmdSelectMultiple"> <StackPanel> <Image Source="pointer.png" Width="35" Height="35"></Image> <TextBlock>Select Multiple</TextBlock> </StackPanel> </RadioButton> </ToolBar> </ToolBarTray> <Border Grid.Column="1" Margin="3" BorderThickness="3" BorderBrush="SteelBlue"> <local:DrawingCanvas x:Name="drawingSurface" Background="White" ClipToBounds="True" MouseLeftButtonDown="drawingSurface_MouseLeftButtonDown" MouseLeftButtonUp="drawingSurface_MouseLeftButtonUp" MouseMove="drawingSurface_MouseMove"></local:DrawingCanvas> </Border> </Grid> </Window>VisualLayer
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Drawing { /// <summary> /// VisualLayer.xaml 的互動邏輯 /// </summary> public partial class VisualLayer : Window { public VisualLayer() { InitializeComponent(); DrawingVisual v = new DrawingVisual(); DrawSquare(v, new Point(10, 10), false); } // Variables for dragging shapes. private bool isDragging = false; private Vector clickOffset; private DrawingVisual selectedVisual; // Variables for drawing the selection square. private bool isMultiSelecting = false; private Point selectionSquareTopLeft; private void drawingSurface_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Point pointClicked = e.GetPosition(drawingSurface); if (cmdAdd.IsChecked == true) { DrawingVisual visual = new DrawingVisual(); DrawSquare(visual, pointClicked, false); drawingSurface.AddVisual(visual); } else if (cmdDelete.IsChecked == true) { DrawingVisual visual = drawingSurface.GetVisual(pointClicked); if (visual != null) drawingSurface.DeleteVisual(visual); } else if (cmdSelectMove.IsChecked == true) { DrawingVisual visual = drawingSurface.GetVisual(pointClicked); if (visual != null) { // Calculate the top-left corner of the square. // This is done by looking at the current bounds and // removing half the border (pen thickness). // An alternate solution would be to store the top-left // point of every visual in a collection in the // DrawingCanvas, and provide this point when hit testing. Point topLeftCorner = new Point( visual.ContentBounds.TopLeft.X + drawingPen.Thickness / 2, visual.ContentBounds.TopLeft.Y + drawingPen.Thickness / 2); DrawSquare(visual, topLeftCorner, true); clickOffset = topLeftCorner - pointClicked; isDragging = true; if (selectedVisual != null && selectedVisual != visual) { // The selection has changed. Clear the previous selection. ClearSelection(); } selectedVisual = visual; } } else if (cmdSelectMultiple.IsChecked == true) { selectionSquare = new DrawingVisual(); drawingSurface.AddVisual(selectionSquare); selectionSquareTopLeft = pointClicked; isMultiSelecting = true; // Make sure we get the MouseLeftButtonUp event even if the user // moves off the Canvas. Otherwise, two selection squares could be drawn at once. drawingSurface.CaptureMouse(); } } // Drawing constants. private Brush drawingBrush = Brushes.AliceBlue; private Brush selectedDrawingBrush = Brushes.LightGoldenrodYellow; private Pen drawingPen = new Pen(Brushes.SteelBlue, 3); private Size squareSize = new Size(30, 30); private DrawingVisual selectionSquare; // Rendering the square. private void DrawSquare(DrawingVisual visual, Point topLeftCorner, bool isSelected) { using (DrawingContext dc = visual.RenderOpen()) { Brush brush = drawingBrush; if (isSelected) brush = selectedDrawingBrush; dc.DrawRectangle(brush, drawingPen, new Rect(topLeftCorner, squareSize)); } } private void drawingSurface_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { isDragging = false; if (isMultiSelecting) { // Display all the squares in this region. RectangleGeometry geometry = new RectangleGeometry( new Rect(selectionSquareTopLeft, e.GetPosition(drawingSurface))); List<DrawingVisual> visualsInRegion = drawingSurface.GetVisuals(geometry); MessageBox.Show(String.Format("You selected {0} square(s).", visualsInRegion.Count)); isMultiSelecting = false; drawingSurface.DeleteVisual(selectionSquare); drawingSurface.ReleaseMouseCapture(); } } private void ClearSelection() { Point topLeftCorner = new Point( selectedVisual.ContentBounds.TopLeft.X + drawingPen.Thickness / 2, selectedVisual.ContentBounds.TopLeft.Y + drawingPen.Thickness / 2); DrawSquare(selectedVisual, topLeftCorner, false); selectedVisual = null; } private void drawingSurface_MouseMove(object sender, MouseEventArgs e) { if (isDragging) { Point pointDragged = e.GetPosition(drawingSurface) + clickOffset; DrawSquare(selectedVisual, pointDragged, true); } else if (isMultiSelecting) { Point pointDragged = e.GetPosition(drawingSurface); DrawSelectionSquare(selectionSquareTopLeft, pointDragged); } } private Brush selectionSquareBrush = Brushes.Transparent; private Pen selectionSquarePen = new Pen(Brushes.Black, 2); private void DrawSelectionSquare(Point point1, Point point2) { selectionSquarePen.DashStyle = DashStyles.Dash; using (DrawingContext dc = selectionSquare.RenderOpen()) { dc.DrawRectangle(selectionSquareBrush, selectionSquarePen, new Rect(point1, point2)); } } } }VisualLayer.xaml.cs
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/63573.html
標籤:其他
下一篇:opencv +數字識別
