WPF绘制图形

利用WPF绘制简单图形,就像Winform那样,参考DrawToolsWPF。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows;
using System.Windows.Input;

namespace WpfApplication1
{
    public class DrawCanvas : Canvas
    {
        private VisualCollection graphics;
        private DrawingContext context;
        private DrawingVisual visual;
        private Point start;

        public DrawCanvas()
        {
            graphics = new VisualCollection(this);
            visual = new DrawingVisual();
            graphics.Add(visual);
            MouseDown += new System.Windows.Input.MouseButtonEventHandler(DrawCanvas_MouseDown);
            MouseMove += new System.Windows.Input.MouseEventHandler(DrawCanvas_MouseMove);
            MouseUp += new System.Windows.Input.MouseButtonEventHandler(DrawCanvas_MouseUp);            
        }

        void DrawCanvas_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Released)
            {
                context = visual.RenderOpen();
                var end = e.GetPosition(this);
                context.DrawLine(new Pen(Brushes.Blue, 2), start, end);
                context.Close();
                this.ReleaseMouseCapture();
            }
         
        }

        void DrawCanvas_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                context = visual.RenderOpen();
                var end = e.GetPosition(this);
                context.DrawLine(new Pen(Brushes.Blue, 2), start, end);
                context.Close();
            }
         

        }

        void DrawCanvas_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                start = e.GetPosition(this);
                this.CaptureMouse();
            }
        }

        /// <summary>
        /// Get number of children: VisualCollection count.
        /// If in-place editing textbox is active, add 1.
        /// </summary>
        protected override int VisualChildrenCount
        {
            get
            {
                int n = graphics.Count; 
                return n;
            }
        }

        /// <summary>
        /// Get visual child - one of GraphicsBase objects
        /// or in-place editing textbox, if it is active.
        /// </summary>
        protected override Visual GetVisualChild(int index)
        {
            if (index < 0 || index >= graphics.Count)
            {
               
                throw new ArgumentOutOfRangeException("index");
            }

            return graphics[index];
        }


    }
}


 

发布了65 篇原创文章 · 获赞 16 · 访问量 56万+

猜你喜欢

转载自blog.csdn.net/jackmacro/article/details/27506047