【WP7】绘图与保存

WP7提供了InkPresenter控件用于绘图,使用InkPresenter控件绘图很简单

1、首先新建一个InkPresenter控件,然后调用CaptureMouse()方法对鼠标进行捕获(这样才能知道绘图时鼠标具体的坐标)

  inkPresenter1.CaptureMouse();

2、添加一个全局变量,用于收集鼠标的坐标集合

  Stroke newStroke;

3、添加三个事件  MouseLeftButtonDown  MouseMove   LostMouseCapture

        private void inkPresenter1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            inkPresenter1.CaptureMouse();//开始捕获鼠标移动路径

            newStroke = new Stroke();
            DrawingAttributes draw = new DrawingAttributes();
            draw.Color = Colors.Blue;
            draw.Width = 10;
            draw.Height = 10;
            draw.OutlineColor = Colors.Red;
            newStroke.DrawingAttributes = draw;
            newStroke.StylusPoints.Add(e.StylusDevice.GetStylusPoints(inkPresenter1));

            this.inkPresenter1.Strokes.Add(newStroke);
        }

        private void inkPresenter1_MouseMove(object sender, MouseEventArgs e)
        {
            Point p = e.GetPosition(inkPresenter1);
            if (p.X < inkPresenter1.Width && p.Y < inkPresenter1.Height && p.X > 0 && p.Y > 0)
            {
                if (newStroke != null)
                {
                    //记录鼠标在inkPresenter1上的移动的点
                    newStroke.StylusPoints.Add(e.StylusDevice.GetStylusPoints(inkPresenter1));
                }
            }
            else
            {
                this.newStroke = null;
            }
        }

        private void inkPresenter1_LostMouseCapture(object sender, MouseEventArgs e)
        {
            this.newStroke = null;
        }

接下来是如何保存控件,这个直接上代码,保存图片到隔离存储控件的 MyPicture/pic1.jpg

  WriteableBitmap 也可以保存其他控件的外观

        WriteableBitmap bitmap = new WriteableBitmap(inkPresenter1, null);
        using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
        {
            string directory = "MyPicture/";
            string jpg = directory + "/pic1.jpg";
            if (!file.DirectoryExists(directory))
            {
                file.CreateDirectory(directory);
            }
            using (IsolatedStorageFileStream stream = file.OpenFile(jpg, System.IO.FileMode.OpenOrCreate))
            {
                bitmap.SaveJpeg(stream, 173, 173, 0, 100);
            }
        }

接下来是访问刚刚保存的图片文件,添加一个Image控件image1用于显示刚刚保存的图片

        using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
        {
            string filename = "MyPicture/pic1.jpg";
            using (IsolatedStorageFileStream stream = file.OpenFile(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                BitmapImage bmp = new BitmapImage();
                bmp.SetSource(stream);
                this.image1.Source = bmp;
            }
        }

 

 

posted @ 2012-12-05 17:32  bomo  阅读(594)  评论(0编辑  收藏  举报