前面幾章介紹了處理適量適中的圖形內容的最佳方法。經過使用幾何圖形、圖畫和路徑,能夠下降2D圖形的開銷。即便正在使用複雜的具備分層效果的組合形狀和漸變畫刷,這種方法也仍然可以正常得很好。ide
然而,這樣設計不適合須要渲染大量圖形元素的繪圖密集型應用程序。例如繪圖程序、演示粒子碰撞的物理模型程序或橫向卷軸形式的遊戲。這些應用程序面臨的不是圖形複雜程度的問題,而純粹是單獨的圖形元素數量的問題。即便使用量級更輕的Geometry對象代替Path元素,須要的開銷也仍會較大地影響應用程序的性能。函數
WPF針對此類問題的解決方案是,使用低級的可視化層(visual layer)模型。基本思想是將每一個圖形元素定義爲一個Visual對象,Visual對象是極輕易級的要素,比Geometry對象或Path對象須要的開銷小。而後可以使用單個元素在窗口中渲染全部可視化對象。工具
1、繪製可視化對象性能
Visual類是抽象類,因此不能建立該類的實例。相反,須要使用繼承自Visual類的某個類,包括UIElement類(該類是WPF元素模型的根)、Viewport3DVisual類(經過該類可顯示3D內容)以及ContainerVisual類(包含其餘可視化對象的基本容器)。但最有用的派生類是DrawingVisual類,該類繼承自ContainerVisual,並添加了支持「繪製」但願放置到可視化對象中的圖形內容的功能。測試
爲使用DrawingVisual類繪製內容,須要調用DrawingVisual.RederOpen()方法。該方法返回一個可用於定義可視化內容的DrawingContext對象。繪製完畢後,須要調用DrawingContext.Close()方法。下面是繪製圖形的完整過程:this
DrawingVisual visual=new DrawingVisual(); DrawingContext dc=visual.RenderOpen(); //(perform drawing here.) dc.Close();
在本質上,DrawingContext類由各類爲可視化對象增長了一些圖形細節的方法構成。可調用這些方法來繪製各類圖形、應用變換以及改變不透明度等。下表列出了DrawingContext類的方法。spa
下面的示例建立了一個可視化對象,該可視化對象包含沒有填充的基本的黑色三角形: 設計
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對象,從而當須要時能夠從新繪製窗口。3d
繪圖代碼的順序很重要。後面的繪圖操做可在已經存在的圖形上繪製內容。PushXxx()方法應用的設置會被應用到後續的繪圖操做中。例如,可以使用PushOpacity()方法改變不透明級別,該設置會影響全部的後續繪圖操做。可以使用Pop()方法恢復最佳的PushXxx()方法。若是屢次調用PushXxx()方法,可一次使用一系列Pop()方法調用關閉它們。code
一旦關閉DrawingContext對象,就不能再修改可視化對象。但可使用DrawingVisual類的Transform和Opacity屬性應用變換或改變整個可視化對象的透明度。若是但願提供全新的內容,能夠再次調用RenderOpen()方法並重復繪製過程。
2、在元素中封裝可視化對象
在可視化層中編寫程序時,最重要的一步是定義可視化對象,但爲了在屏幕上實際顯示可視內容,這還不夠。爲顯示可視化對象,還須要藉助於功能完備的WPF元素,WPF元素將可視化對象添加到可視化樹中。乍一看,這好像下降了可視化層變成的優勢——畢竟,避免使用元素並避免它們的巨大開銷不正是使用可視化層的所有目的嗎?然而,單個元素具備顯示任意數量可視化對象的能力。所以,能夠很容易地建立只包含一兩個元素,但卻駐留了幾千個可視化對象的窗口。
爲在元素中駐留可視化對象,須要執行一下任務:
當重寫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)); } }
這就是在窗口中顯示可視化對象須要作的所有工做:渲染可視化對象的代碼,以及處理必需的跟蹤細節的內容。若是但願爲可視化對象添加交互功能,還須要完成其餘一些工做。
3、命中測試
繪製正方形的應用程序不只容許繪製正方形,還容許用戶移動和刪除以及繪製的正方形。爲了執行這些任務,須要編寫代碼以截獲鼠標單擊,並查找位於可單擊位置的可視化對象。該任務被稱爲命中測試(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); } }
4、複雜的命中測試
在上面的示例中,命中測試代碼始終返回最上面的可視化對象(若是單擊空白處,就返回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; } } }
<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>
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)); } } } }