【WPF學習】第四十五章 可視化對象

来源:https://www.cnblogs.com/Peter-Luo/archive/2020/02/19/12333089.html
-Advertisement-
Play Games

前面幾章介紹了處理適量適中的圖形內容的最佳方法。通過使用幾何圖形、圖畫和路徑,可以降低2D圖形的開銷。即使正在使用複雜的具有分層效果的組合形狀和漸變畫刷,這種方法也仍然能夠正常得很好。 然而,這樣設計不適合需要渲染大量圖形元素的繪圖密集型應用程式。例如繪圖程式、演示粒子碰撞的物理模型程式或橫向卷軸形 ...


  前面幾章介紹了處理適量適中的圖形內容的最佳方法。通過使用幾何圖形、圖畫和路徑,可以降低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 squareSi

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 什麼是RPC RPC (Remote Procedure Call Protocol), 遠程過程調用,通俗的解釋就是:客戶端在不知道調用細節的情況下,調用存在於遠程電腦上的某個對象,就像調用本地應用程式中的對象一樣,不需要瞭解底層網路技術的協議。 簡單的整體工作流程 請求端發送一個調用的數據包, ...
  • 在dubbo中,關於註冊中心Registry的有關實現封裝在了dubbo registry模塊中。提供者(Provider)個消費者(Consumer)都是通過註冊中心進行資源的調度。當服務啟動時,provider會調用註冊中心的register方法將自己的服務通過url的方式發佈到註冊中心,而co ...
  • 在網路傳輸中,怎麼確保通道連接的可用性是一個很重要的問題,簡單的說,在網路通信中有客戶端和服務端,一個負責發送請求,一個負責接收請求,在保證連接有效性的背景下,這兩個物體扮演了什麼角色,心跳機制能有效的保證連接的可用性,那它的機制是什麼,下文中將會詳細講解。 網路層的可用性 首先講一下TCP,在du ...
  • 在上文中介紹了基礎類AbstractRegistry類的解釋,在本篇中將繼續介紹該包下的其他類。 FailbackRegistry 該類繼承了AbstractRegistry,AbstractRegistry中的註冊訂閱等方法,實際上就是一些記憶體緩存的變化,而真正的註冊訂閱的實現邏輯在Failbac ...
  • [TOC] python是數據分析的主要工具,它包含的數據結構和數據處理工具的設計讓python在數據分析領域變得十分快捷。它以NumPy為基礎,並對於需要類似 for迴圈 的大量數據處理的問題有非常快捷的數組處理函數。 但是pandas最擅長的領域還是在處理表格型二維以上不同數據類型數據。 基本導 ...
  • 從今天開始,將會逐步介紹關於DUbbo的有關知識。首先先簡單介紹一下DUbbo的整體概述。 概述 Dubbo是SOA(面向服務架構)服務治理方案的核心框架。用於分散式調用,其重點在於分散式的治理。 簡單的來說,可以把它分為四個角色。服務提供方(Provider)、服務消費方(Consumer)、註冊 ...
  • 在上一篇文章 Dubbo之服務暴露分析 中介紹了當遠程暴露時,如果有註冊中心,需要在服務暴露後再將服務註冊到註冊中心。該篇將介紹該功能的有關步驟。 註冊的起點 在 方法包含了服務導出,註冊,以及數據訂閱等邏輯。其中服務註冊先調用 方法。 可以看出,服務註冊主要包括兩部分, 獲取註冊中心實例 和 向註 ...
  • Dubbo的服務暴露是一個重要的特性,瞭解其機制很重要。之前有很多人寫了有關的源代碼分析,在本文中不再重新分析。官方文檔中的一篇寫的就很好,本文主要是有關內容進行補充與總結。 傳送門: "服務導出" 為什麼要服務暴露 服務暴露分為遠程暴露和本地暴露。在遠程服務暴露中會將服務信息上傳到註冊中心。這時客 ...
一周排行
    -Advertisement-
    Play Games
  • Timer是什麼 Timer 是一種用於創建定期粒度行為的機制。 與標準的 .NET System.Threading.Timer 類相似,Orleans 的 Timer 允許在一段時間後執行特定的操作,或者在特定的時間間隔內重覆執行操作。 它在分散式系統中具有重要作用,特別是在處理需要周期性執行的 ...
  • 前言 相信很多做WPF開發的小伙伴都遇到過表格類的需求,雖然現有的Grid控制項也能實現,但是使用起來的體驗感並不好,比如要實現一個Excel中的表格效果,估計你能想到的第一個方法就是套Border控制項,用這種方法你需要控制每個Border的邊框,並且在一堆Bordr中找到Grid.Row,Grid. ...
  • .NET C#程式啟動閃退,目錄導致的問題 這是第2次踩這個坑了,很小的編程細節,容易忽略,所以寫個博客,分享給大家。 1.第一次坑:是windows 系統把程式運行成服務,找不到配置文件,原因是以服務運行它的工作目錄是在C:\Windows\System32 2.本次坑:WPF桌面程式通過註冊表設 ...
  • 在分散式系統中,數據的持久化是至關重要的一環。 Orleans 7 引入了強大的持久化功能,使得在分散式環境下管理數據變得更加輕鬆和可靠。 本文將介紹什麼是 Orleans 7 的持久化,如何設置它以及相應的代碼示例。 什麼是 Orleans 7 的持久化? Orleans 7 的持久化是指將 Or ...
  • 前言 .NET Feature Management 是一個用於管理應用程式功能的庫,它可以幫助開發人員在應用程式中輕鬆地添加、移除和管理功能。使用 Feature Management,開發人員可以根據不同用戶、環境或其他條件來動態地控制應用程式中的功能。這使得開發人員可以更靈活地管理應用程式的功 ...
  • 在 WPF 應用程式中,拖放操作是實現用戶交互的重要組成部分。通過拖放操作,用戶可以輕鬆地將數據從一個位置移動到另一個位置,或者將控制項從一個容器移動到另一個容器。然而,WPF 中預設的拖放操作可能並不是那麼好用。為瞭解決這個問題,我們可以自定義一個 Panel 來實現更簡單的拖拽操作。 自定義 Pa ...
  • 在實際使用中,由於涉及到不同編程語言之間互相調用,導致C++ 中的OpenCV與C#中的OpenCvSharp 圖像數據在不同編程語言之間難以有效傳遞。在本文中我們將結合OpenCvSharp源碼實現原理,探究兩種數據之間的通信方式。 ...
  • 一、前言 這是一篇搭建許可權管理系統的系列文章。 隨著網路的發展,信息安全對應任何企業來說都越發的重要,而本系列文章將和大家一起一步一步搭建一個全新的許可權管理系統。 說明:由於搭建一個全新的項目過於繁瑣,所有作者將挑選核心代碼和核心思路進行分享。 二、技術選擇 三、開始設計 1、自主搭建vue前端和. ...
  • Csharper中的表達式樹 這節課來瞭解一下表示式樹是什麼? 在C#中,表達式樹是一種數據結構,它可以表示一些代碼塊,如Lambda表達式或查詢表達式。表達式樹使你能夠查看和操作數據,就像你可以查看和操作代碼一樣。它們通常用於創建動態查詢和解析表達式。 一、認識表達式樹 為什麼要這樣說?它和委托有 ...
  • 在使用Django等框架來操作MySQL時,實際上底層還是通過Python來操作的,首先需要安裝一個驅動程式,在Python3中,驅動程式有多種選擇,比如有pymysql以及mysqlclient等。使用pip命令安裝mysqlclient失敗應如何解決? 安裝的python版本說明 機器同時安裝了 ...