public ColorSelection(InkCanvas inkCanvas)
 {
     _inkCanvas = inkCanvas;
     Red = false;
     Green = false;
     Blue = false;
 }
 public SelectionAdorner(StrokeCollection selectedStrokes, InkCanvas inkcanvas)
 {
     InitializeComponent();
     referencedStrokes = selectedStrokes;
     referencedCanvas = inkcanvas;
     setupSelectionAdorner();
 }
        public static async Task<StorageFile> SaveScreenshotTemporaryAsync(this Panel parent, InkCanvas inkCanvas = null, List<FrameworkElement> excludedElements = null)
        {
            StorageFile tempFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("dataFile.png", CreationCollisionOption.ReplaceExisting);
            await SaveScreenshotInternal(tempFile, parent, inkCanvas, excludedElements);

            return tempFile;
        }
Beispiel #4
0
        public void SetInkCanvas(Window dmWindow, Window playerWindow, InkCanvas dmView, InkCanvas playerView)
        {
            _dmWindow     = dmWindow;
            _playerWindow = playerWindow;

            _dispatcher = Dispatcher.CurrentDispatcher;
            ErasePoints = new List <Rect>();
            _dmView     = dmView;
            _playerView = playerView;

            _dmView.EditingMode     = InkCanvasEditingMode.None;
            _playerView.EditingMode = InkCanvasEditingMode.None;

            _dmView.MouseMove += _dmView_MouseMove;
            FillMap();
        }
Beispiel #5
0
        public void ActivateEraser(InkCanvas inkCanvas, Rectangle rectangle_Eraser, TranslateTransform translateTransform)
        {
            CurrentInkCanvas = inkCanvas;
            Rectangle_Eraser = rectangle_Eraser;
            TranslateTransform_Rectangle_Eraser = translateTransform;

            switch (SelectedEraser)
            {
            case 0:
                CurrentInkCanvas.InkPresenter.InputProcessingConfiguration.Mode            = InkInputProcessingMode.Erasing;
                CurrentInkCanvas.InkPresenter.InputProcessingConfiguration.RightDragAction = InkInputRightDragAction.AllowProcessing;
                CurrentInkCanvas.InkPresenter.UnprocessedInput.PointerPressed  -= UnprocessedInputEraser_PointerPressed;
                CurrentInkCanvas.InkPresenter.UnprocessedInput.PointerMoved    -= UnprocessedInputEraser_PointerMoved;
                CurrentInkCanvas.InkPresenter.UnprocessedInput.PointerReleased -= UnprocessedInputEraser_PointerReleased;
                break;

            case 1:
                EraserWidth = 12;

                CurrentInkCanvas.InkPresenter.InputProcessingConfiguration.Mode            = InkInputProcessingMode.None;
                CurrentInkCanvas.InkPresenter.InputProcessingConfiguration.RightDragAction = InkInputRightDragAction.LeaveUnprocessed;
                CurrentInkCanvas.InkPresenter.UnprocessedInput.PointerPressed  += UnprocessedInputEraser_PointerPressed;
                CurrentInkCanvas.InkPresenter.UnprocessedInput.PointerMoved    += UnprocessedInputEraser_PointerMoved;
                CurrentInkCanvas.InkPresenter.UnprocessedInput.PointerReleased += UnprocessedInputEraser_PointerReleased;
                break;

            case 2:
                EraserWidth = 25;

                CurrentInkCanvas.InkPresenter.InputProcessingConfiguration.Mode            = InkInputProcessingMode.None;
                CurrentInkCanvas.InkPresenter.InputProcessingConfiguration.RightDragAction = InkInputRightDragAction.LeaveUnprocessed;
                CurrentInkCanvas.InkPresenter.UnprocessedInput.PointerPressed  += UnprocessedInputEraser_PointerPressed;
                CurrentInkCanvas.InkPresenter.UnprocessedInput.PointerMoved    += UnprocessedInputEraser_PointerMoved;
                CurrentInkCanvas.InkPresenter.UnprocessedInput.PointerReleased += UnprocessedInputEraser_PointerReleased;
                break;

            case 3:
                EraserWidth = 37;

                CurrentInkCanvas.InkPresenter.InputProcessingConfiguration.Mode            = InkInputProcessingMode.None;
                CurrentInkCanvas.InkPresenter.InputProcessingConfiguration.RightDragAction = InkInputRightDragAction.LeaveUnprocessed;
                CurrentInkCanvas.InkPresenter.UnprocessedInput.PointerPressed  += UnprocessedInputEraser_PointerPressed;
                CurrentInkCanvas.InkPresenter.UnprocessedInput.PointerMoved    += UnprocessedInputEraser_PointerMoved;
                CurrentInkCanvas.InkPresenter.UnprocessedInput.PointerReleased += UnprocessedInputEraser_PointerReleased;
                break;
            }
        }
Beispiel #6
0
        /// <summary>
        /// Скользящее рисование фигуры
        /// </summary>
        /// <param name="currentPoint">Текущая координата фигуры</param>
        public void DrawingShape(Point currentPoint)
        {
            switch (this._drawMode)
            {
            case BOADR_DRAW_SHAPE.POLYLINE:
                this._pointCnt++;
                if (this._pointCnt % 2 == 0)
                {
                    ((Polyline)this._currentShape).Points.Add(currentPoint);
                    this._pointCnt = 0;
                }
                break;

            case BOADR_DRAW_SHAPE.LINE:
                ((Line)this._currentShape).X2 = currentPoint.X;
                ((Line)this._currentShape).Y2 = currentPoint.Y;
                break;

            case BOADR_DRAW_SHAPE.RECTANGLE:
            case BOADR_DRAW_SHAPE.ROUND_RECTANGLE:
            case BOADR_DRAW_SHAPE.ELLIPSE:
                double width  = currentPoint.X - this._beginPoint.X;
                double height = currentPoint.Y - this._beginPoint.Y;

                //Нормализация фигуры

                if (width < 0 && height < 0)
                {
                    InkCanvas.SetLeft(this._currentShape, currentPoint.X);
                    InkCanvas.SetTop(this._currentShape, currentPoint.Y);
                }
                else if (width > 0 && height < 0)
                {
                    InkCanvas.SetTop(this._currentShape, currentPoint.Y);
                }
                else if (width < 0 && height > 0)
                {
                    InkCanvas.SetLeft(this._currentShape, currentPoint.X);
                }
                this._currentShape.Width  = Math.Abs(width);
                this._currentShape.Height = Math.Abs(height);
                break;

            default:
                throw new ApplicationException("Не известный тип фигуры");
            }
        }
        //レイヤー関連
        private void layerButtonClick(object sender, RoutedEventArgs e)
        {
            //現在のレイヤー関連を保持
            Button    beforeLayerButton = FindName(nowLayer + "Button") as Button;
            InkCanvas beforeLayerInk    = nowLayerInk;
            Canvas    beforeLayerStamp  = nowLayerStamp;

            //クリックされたレイヤー情報
            Button nowLayerButton = sender as Button;
            String clickedLayer   = nowLayerButton.Content.ToString();

            nowLayer      = clickedLayer;
            nowLayerInk   = FindName("inkCanvas" + clickedLayer) as InkCanvas;
            nowLayerStamp = FindName("StampCanvas" + clickedLayer) as Canvas;

            //表示系の切り替え
            nowLayerInk.Visibility      = Visibility.Visible;
            nowLayerStamp.Visibility    = Visibility.Visible;
            beforeLayerInk.Visibility   = Visibility.Collapsed;
            beforeLayerInk.EditingMode  = InkCanvasEditingMode.None;
            nowInkButton.BorderBrush    = new SolidColorBrush(Colors.LightGray);
            CMItems[0].IsChecked        = false;
            CMItems[1].IsChecked        = false;
            EraseButton.IsChecked       = false;
            beforeLayerStamp.Visibility = Visibility.Collapsed;
            nowLayerButton.IsEnabled    = false;
            beforeLayerButton.IsEnabled = true;

            //コマの透過関連
            int  i;
            Line line;

            for (i = 0; i < 10; i++)
            {
                line = FindName(thumbs[i].Name + "Line") as Line;
                if (thumbsLayer[i].Equals(nowLayer))
                {
                    thumbs[i].Opacity = 1;
                    line.Opacity      = 1;
                }
                else
                {
                    thumbs[i].Opacity = 0.4;
                    line.Opacity      = 0.4;
                }
            }
        }
Beispiel #8
0
        private void MainInkCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            if (_drawerIsMove == true)
            {
                Point endP = e.GetPosition(MainInkCanvas);

                if (_drawerLastStroke != null && _mode != DrawMode.Ray && _mode != DrawMode.Text)
                {
                    StrokeCollection collection = new StrokeCollection();
                    collection.Add(_drawerLastStroke);
                    Push(_history, new StrokesHistoryNode(collection, StrokesHistoryNodeType.Added));
                }

                if (_drawerLastStroke != null && (_mode == DrawMode.Ray || _mode == DrawMode.Text))
                {
                    //us animation?

                    /*
                     * var ani = new DoubleAnimation(1, 1, Duration4);
                     * ani.Completed += (obj,arg)=> { MainInkCanvas.Strokes.Remove(_drawerLastStroke); };
                     * MainInkCanvas.BeginAnimation(OpacityProperty, ani);
                     */
                    MainInkCanvas.Strokes.Remove(_drawerLastStroke);
                }

                if (_mode == DrawMode.Text)
                {
                    //resize drawer text box
                    _drawerTextBox.Width  = Math.Abs(endP.X - _drawerIntPos.X);
                    _drawerTextBox.Height = Math.Abs(endP.Y - _drawerIntPos.Y);

                    if (_drawerTextBox.Width <= 100 || _drawerTextBox.Height <= 40)
                    {
                        _drawerTextBox.Width  = 100;
                        _drawerTextBox.Height = 40;
                    }

                    InkCanvas.SetLeft(_drawerTextBox, Math.Min(_drawerIntPos.X, endP.X));
                    InkCanvas.SetTop(_drawerTextBox, Math.Min(_drawerIntPos.Y, endP.Y));

                    _drawerTextBox.Focus();
                }

                _drawerIsMove        = false;
                _ignoreStrokesChange = false;
            }
        }
Beispiel #9
0
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            glControlHost              = GetTemplateChild("GLControlHost") as WindowsFormsHost;
            glControlHost.SizeChanged += GlControlHost_SizeChanged;
            glControlHost.Child        = glControl;

            Tabs = GetTemplateChild("Tabs") as IBTabControl;
            Tabs.ItemsChanged     += Tabs_ItemsChanged;
            Tabs.SelectionChanged += Tabs_SelectionChanged;
            Tabs.Items.Add(new SubTabItem()
            {
                isDummyItem = true, Header = "*** NoItems ***"
            });

            Overlay = new Window()
            {
                WindowStyle = WindowStyle.None, AllowsTransparency = true, Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0))
            };
            canvas                 = new InkCanvas();
            canvas.Background      = new SolidColorBrush(Color.FromArgb(1, 127, 127, 127));
            canvas.EditingMode     = InkCanvasEditingMode.None;
            canvas.UseCustomCursor = true;
            root = new Grid();
            root.Children.Add(canvas);
            overlayCanvas = new Canvas();
            root.Children.Add(overlayCanvas);
            Overlay.Content = root;

            Overlay.MouseEnter       += Canvas_MouseEnter;
            canvas.MouseEnter        += Canvas_MouseEnter;
            canvas.PreviewMouseDown  += Overlay_MouseDown;
            canvas.MouseWheel        += Overlay_MouseWheel;
            canvas.PreviewStylusMove += Overlay_StylusMove;
            canvas.PreviewMouseMove  += Overlay_MouseMove;
            canvas.PreviewMouseUp    += Overlay_MouseUp;
            canvas.StylusUp          += Canvas_StylusUp;
            canvas.StylusOutOfRange  += Overlay_StylusOutOfRange;
            canvas.StylusLeave       += Canvas_StylusLeave;
            Overlay.Show();

            OpenedElements.CollectionChanged += OpenedElements_CollectionChanged;
            SetOwner();

            glControl.Refresh();
        }
Beispiel #10
0
        public async Task PopulateHighscoresAsync()
        {
            var hs = new Services.Highscore();
            await hs.SaveAsync(GameState.PlayerId, GameState.OverallElapsedTime, GameState.Difficulty);

            var scores = await hs.LoadAsync();

            foreach (var item in scores.Where(x => x.Difficulty == GameState.Difficulty).OrderBy(x => x.ElapsedTime))
            {
                var g = new Grid();

                g.ColumnDefinitions.Add(new ColumnDefinition()
                {
                    Width = new Windows.UI.Xaml.GridLength(1, Windows.UI.Xaml.GridUnitType.Star)
                });
                g.ColumnDefinitions.Add(new ColumnDefinition()
                {
                    Width = new Windows.UI.Xaml.GridLength(1, Windows.UI.Xaml.GridUnitType.Star)
                });

                var t = new InkCanvas()
                {
                    Width = 250, Height = 100
                };
                await hs.LoadPlayerSignatureAsync(t, item.PlayerId);

                Grid.SetColumn(t, 0);

                var t2 = new TextBlock()
                {
                    FontSize = 28, Text = string.Format("⌛ {0:mm\\:ss\\,ff}", item.ElapsedTime), HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center
                };
                if (item.PlayerId == GameState.PlayerId)
                {
                    g.Background = new SolidColorBrush(Colors.Orange);
                }

                Grid.SetColumn(t2, 1);

                g.Children.Add(t);
                g.Children.Add(t2);

                highscores.Children.Add(g);
            }

            return;
        }
Beispiel #11
0
        public override void Perform()
        {
            ApplicationGesture[] allAppGestures = (ApplicationGesture[])Enum.GetValues(ApplicationGesture.Up.GetType());

            //Get a number of gestures we will enable
            int gestureCount = CountIndex % (allAppGestures.Length - 2) + 1;

            ArrayList enableGesturesArrayList = new ArrayList();

            //Fill the arraylist with the number of gestures we want to enable
            while (gestureCount > 0)
            {
                int index = GestureIndex % allAppGestures.Length;
                GestureIndex++;

                //If adding an AllGestures,reject it and continue to get the next gesture to add
                if (allAppGestures[index] == ApplicationGesture.AllGestures)
                {
                    continue;
                }

                bool gestureExists = false;

                //Check if the appgesture is already added. if there are duplicates, API throws exception
                for (int i = 0; i < enableGesturesArrayList.Count; i++)
                {
                    ApplicationGesture currentGesture = (ApplicationGesture)enableGesturesArrayList[i];
                    //Don't add something that already exists in the enableGestures list
                    if (allAppGestures[index] == currentGesture)
                    {
                        gestureExists = true;
                        break;
                    }
                }
                //Not added so far, add and continue
                if (gestureExists == false)
                {
                    enableGesturesArrayList.Add(allAppGestures[index]);
                    gestureCount--; //One less thing to add
                }
            }

            ApplicationGesture[] applicationGestureArray = (ApplicationGesture[])enableGesturesArrayList.ToArray(ApplicationGesture.ArrowDown.GetType());

            //Sets the application gestures that the InkCanvas recognizes.
            InkCanvas.SetEnabledGestures(applicationGestureArray);
        }
Beispiel #12
0
        public static void ExportToPng(Uri path, InkCanvas Surface)
        {
            if (path == null)
            {
                return;
            }

            // Save current canvas transform
            Transform transform = Surface.LayoutTransform;

            // reset current transform (in case it is scaled or rotated)
            Surface.LayoutTransform = null;

            // Get the size of canvas
            Size size = new Size(Surface.ActualWidth, Surface.ActualHeight);

            // Measure and arrange the surface
            // VERY IMPORTANT
            Surface.Measure(size);
            Surface.Arrange(new Rect(size));

            // Create a render bitmap and push the surface to it
            RenderTargetBitmap renderBitmap =
                new RenderTargetBitmap(
                    (int)size.Width,
                    (int)size.Height,
                    96d,
                    96d,
                    PixelFormats.Pbgra32);

            renderBitmap.Render(Surface);

            // Create a file stream for saving image
            using (FileStream outStream = new FileStream(path.LocalPath, FileMode.Create))
            {
                // Use png encoder for our data
                PngBitmapEncoder encoder = new PngBitmapEncoder();
                // push the rendered bitmap to it
                encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                // save the data to the stream
                encoder.Save(outStream);
            }

            // Restore previously saved layout
            Surface.LayoutTransform = transform;
        }
Beispiel #13
0
        public void switchState(StateUpdate_Model d)
        {
            this.gameInfoBar.switchtoPassiv(d);
            drawView.Dispatcher.Invoke(() =>
            {
                InkCanvas b = new InkCanvas();
                UserControl_WriteToPassif temp = new UserControl_WriteToPassif();
                foreach (var s in drawView.surfaceDessin.Strokes)
                {
                    b.Strokes.Add(s);
                }

                this.DrawingArea.Children.Clear();
                temp.doc.Children.Add(b);
                this.DrawingArea.Children.Add(temp);
            });
        }
Beispiel #14
0
        public void Export(InkCanvas canvas, ImageFormat media)
        {
            Stream         exportFileStream;
            SaveFileDialog fileDialog = new SaveFileDialog
            {
                Filter = media == ImageFormat.Png ? "Files | *.png;" : "Files | *.jpg; *.jpeg;"
            };

            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                using (exportFileStream = fileDialog.OpenFile())
                {
                    ExportWithoutSaving(canvas, media, exportFileStream);
                    exportFileStream.Close();
                }
            }
        }
Beispiel #15
0
        public async void SaveCanvas(InkCanvas canvas, string name, string pageNr = "")
        {
            try {
                if (canvas == null || canvas.InkPresenter.StrokeContainer.GetStrokes().Count <= 0)
                {
                    return;
                }
                var folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("folder_" + name, CreationCollisionOption.OpenIfExists);

                var file = await folder.CreateFileAsync(name + pageNr + App.SettingStrings["ink"], CreationCollisionOption.ReplaceExisting);

                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite)) {
                    await canvas.InkPresenter.StrokeContainer.SaveAsync(stream);
                }
            }
            catch (Exception) { }
        }
Beispiel #16
0
        /// <summary>
        /// Load strokes from .ink file to InkCanvas
        /// </summary>
        /// <param name="inkCanvas">InkCanvas Object</param>
        /// <param name="location">PickerLocationId</param>
        /// <returns>Task</returns>
        public static async Task LoadInkFile(InkCanvas inkCanvas, PickerLocationId location)
        {
            var picker = new FileOpenPicker
            {
                SuggestedStartLocation = location
            };

            picker.FileTypeFilter.Add(".ink");
            var pickedFile = await picker.PickSingleFileAsync();

            if (pickedFile != null)
            {
                var file = await pickedFile.OpenReadAsync();

                await inkCanvas.InkPresenter.StrokeContainer.LoadAsync(file);
            }
        }
Beispiel #17
0
        /// <summary>
        /// Called after the behavior is attached to the <see cref="Microsoft.Xaml.Interactivity.Behavior.AssociatedObject" />.
        /// </summary>
        protected override void OnAttached()
        {
            if (this.MapControl != null)
            {
                this.MapControl.SizeChanged += this.MapControlOnSizeChanged;

                this.inkingCanvas = new InkCanvas {
                    IsHitTestVisible = false
                };

                Canvas.SetZIndex(this.inkingCanvas, 99999);

                this.InitializeInkingCanvas();

                this.MapControl.Children.Add(this.inkingCanvas);
            }
        }
Beispiel #18
0
        /// <summary>
        /// Loads player signature based in his or her GUID
        /// </summary>
        /// <param name="ink"></param>
        /// <param name="playerId"></param>
        /// <returns></returns>
        public async Task LoadPlayerSignatureAsync(InkCanvas ink, string playerId)
        {
            var file = await ApplicationData.Current.LocalFolder.GetFileAsync(playerId + ".isf");

            if (file != null)
            {
                var stream = await file.OpenAsync(FileAccessMode.Read);

                using (var inputStream = stream.GetInputStreamAt(0))
                {
                    await ink.InkPresenter.StrokeContainer.LoadAsync(inputStream);
                }
                stream.Dispose();
            }

            return;
        }
 public KeyFrameAnnotation()
 {
     this.InitializeComponent();
     this.MaxWidth  = 400;
     this.MaxHeight = 400;
     this.MinHeight = 100;
     this.MinWidth  = 100;
     //_controlPanel.setInkFrame(_inkFrame);
     _inkCollector                = _inkFrame.InkCollector;
     InkCanvasAnnotation          = _inkFrame._inkCanvas;
     _inkFrame.rectangle1.Opacity = 0.5;
     InkCanvasAnnotation.Opacity  = 0.5;
     InkCanvasAnnotation.DefaultDrawingAttributes.Color      = Colors.Red;
     InkCanvasAnnotation.DefaultDrawingAttributes.Width      =
         InkCanvasAnnotation.DefaultDrawingAttributes.Height = 5;
     InkCanvasAnnotation.StrokeCollected += new InkCanvasStrokeCollectedEventHandler(InkCanvasAnnotation_StrokeCollected);
 }
Beispiel #20
0
 public InkCanvasLayer()
 {
     TopCanvas     = new InkCanvas();
     StrokeBuilder = new InkStrokeBuilder();
     TopCanvas.InkPresenter.InputDeviceTypes = CoreInputDeviceTypes.Mouse | CoreInputDeviceTypes.Pen | CoreInputDeviceTypes.Touch;
     ChangeCanvasModel(true);
     TopCanvas.InkPresenter.UpdateDefaultDrawingAttributes(new InkDrawingAttributes()
     {
         Color = Colors.Black
     });
     TopCanvas.InkPresenter.UnprocessedInput.PointerPressed  += UnprocessedInput_PointerPressed;
     TopCanvas.InkPresenter.UnprocessedInput.PointerMoved    += UnprocessedInput_PointerMoved;
     TopCanvas.InkPresenter.UnprocessedInput.PointerReleased += UnprocessedInput_PointerReleased;
     TopCanvas.InkPresenter.UnprocessedInput.PointerHovered  += UnprocessedInput_PointerHovered;
     TopCanvas.InkPresenter.UnprocessedInput.PointerLost     += UnprocessedInput_PointerLost;
     TopCanvas.KeyDown += TopCanvas_KeyDown;
 }
        private static void PenSize(DependencyObject d,
                                    DependencyPropertyChangedEventArgs e)
        {
            InkCanvas ink = d as InkCanvas;

            if (ink == null)
            {
                return;
            }

            InkDrawingAttributes drawingAttributes = ink.InkPresenter.CopyDefaultDrawingAttributes();
            var size = Convert.ToInt32(e.NewValue);

            drawingAttributes.Size = new Size(size, size);

            ink.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
        }
Beispiel #22
0
        private void FormField_PointerPressed(object sender, PointerRoutedEventArgs e)
        {
            var    formField    = sender as Grid;
            string canvasPrefix = formField.Name;

            var canvas = this.FindName($"{canvasPrefix}Canvas") as InkCanvas;

            inkToolbar.TargetInkCanvas = canvas;
            currentCanvas = canvas;

            foreach (string prefix in prefixes)
            {
                ToggleFormFieldText(prefix);
            }

            ToggleFormFieldCanvas(canvasPrefix);
        }
Beispiel #23
0
        public async static Task LoadAsync(this InkCanvas inkCanvas, string fileName, StorageFolder folder = null)
        {
            folder = folder ?? ApplicationData.Current.TemporaryFolder;
            var file = await folder.TryGetItemAsync(fileName) as StorageFile;

            if (file != null)
            {
                try
                {
                    using (var stream = await file.OpenSequentialReadAsync())
                    {
                        await inkCanvas.InkPresenter.StrokeContainer.LoadAsync(stream);
                    }
                }
                catch { }
            }
        }
        private void cvs_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            Shape shapeToAdd = null;
            Brush b          = new SolidColorBrush(this.cvs.DefaultDrawingAttributes.Color);

            if (this.cvs != null)
            {
                if (rectShape.IsChecked == true)
                {
                    shapeToAdd = new Rectangle()
                    {
                        Fill = b, Height = 100, Width = 100, RadiusX = 0, RadiusY = 0
                    };
                }
                else if (circleShape.IsChecked == true)
                {
                    shapeToAdd = new Ellipse()
                    {
                        Fill = b, Height = 100, Width = 100
                    };
                }
                else if (lineShape.IsChecked == true)
                {
                    shapeToAdd = new Line()
                    {
                        Height          = 24, Width = 210,
                        StrokeThickness = 20, Stroke = b,
                        X1 = 5, X2 = 200, Y1 = 5, Y2 = 5,
                        StrokeStartLineCap = PenLineCap.Round, StrokeEndLineCap = PenLineCap.Round
                    };
                }
            }

            if (rectShape.IsChecked == true || circleShape.IsChecked == true)
            {
                InkCanvas.SetLeft(shapeToAdd, e.GetPosition(this.cvs).X - 50);
                InkCanvas.SetTop(shapeToAdd, e.GetPosition(this.cvs).Y - 50);
            }
            else
            {
                InkCanvas.SetLeft(shapeToAdd, e.GetPosition(this.cvs).X);
                InkCanvas.SetTop(shapeToAdd, e.GetPosition(this.cvs).Y - 12);
            }

            this.cvs.Children.Add(shapeToAdd);
        }
Beispiel #25
0
        public override void RemoveHandle()
        {
            base.RemoveHandle();

            ContainerClass.MousePosition = null;

            if (CurrentInkCanvas != null)
            {
                CurrentInkCanvas.EditingMode = InkCanvasEditingMode.None;
                CurrentInkCanvas             = null;
            }

            if (ContainerClass.LastGrid != null)
            {
                ContainerClass.LastGrid = null;
            }
        }
Beispiel #26
0
        public static async Task <string> Recognize(this InkCanvas inkCanvas)
        {
            var strokes = inkCanvas.InkPresenter.StrokeContainer;

            if (strokes.GetStrokes().Any())
            {
                var recognizer = new InkRecognizerContainer();
                var results    = await recognizer.RecognizeAsync(strokes, InkRecognitionTarget.All);

                var candidates = results.Select(x => x.GetTextCandidates().First());
                return(string.Join(" ", candidates));
            }
            else
            {
                return(string.Empty);
            }
        }
Beispiel #27
0
        /// <summary>
        /// Loads a signature for the specified check/person
        /// </summary>
        private async void loadSig(String date2, int shift, String pather, InkCanvas inky)
        {
            try
            {
                StorageFolder mainFolder = await KnownFolders.MusicLibrary.CreateFolderAsync(date2, CreationCollisionOption.OpenIfExists);

                IReadOnlyList <StorageFolder> Folders = await mainFolder.GetFoldersAsync();

                List <String> folderNames = new List <string>();

                foreach (StorageFolder thisFolder in Folders)
                {
                    folderNames.Add(thisFolder.Name);
                }
                ObservableCollection <String> checkNames = new ObservableCollection <string>();
                if (folderNames.Contains("Morning"))
                {
                    checkNames = ShiftSource;
                }
                else if (folderNames.Contains("Shift Start"))
                {
                    checkNames = newShiftSource;
                }

                String        shiftName = checkNames[shift];
                StorageFolder sigFolder = await mainFolder.CreateFolderAsync(shiftName, CreationCollisionOption.OpenIfExists);

                StorageFile newFile = await sigFolder.CreateFileAsync(pather, CreationCollisionOption.OpenIfExists);


                // User selects a file and picker returns a reference to the selected file.
                if (newFile != null)
                {
                    // Open a file stream for reading.
                    IRandomAccessStream stream = await newFile.OpenAsync(Windows.Storage.FileAccessMode.Read);

                    // Read from file.
                    using (var inputStream = stream.GetInputStreamAt(0))
                    {
                        await inky.InkPresenter.StrokeContainer.LoadAsync(inputStream);
                    }
                    stream.Dispose();
                }
            }
            catch { }
        }
        private static void PenColor(DependencyObject d,
                                     DependencyPropertyChangedEventArgs e)
        {
            InkCanvas ink = d as InkCanvas;

            if (ink == null)
            {
                return;
            }

            InkDrawingAttributes drawingAttributes = ink.InkPresenter.CopyDefaultDrawingAttributes();
            var brush = e.NewValue as SolidColorBrush;

            drawingAttributes.Color = brush.Color;

            ink.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
        }
Beispiel #29
0
 public void MouseWheel(InkCanvas inkCanvas, MouseWheelEventArgs e)
 {
     if (ProcessRepeateSelectionState != RepeateSelectionState.WaitingEndPoint)
     {
         return;
     }
     if (e.Delta < 0 && _repetitions.Count > 1)
     {
         RemoveCopy(inkCanvas);
         Refresh();
     }
     else if (e.Delta > 0 && _repetitions.Count < 100)
     {
         AddCopy(inkCanvas);
         Refresh();
     }
 }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            this._centerCanvas = Template.FindName("PART_CenterCanvas", this) as InkCanvas;

            this._imageCenter = Template.FindName("PART_ImageCenter", this) as Image;

            grid_Mouse_drag = Template.FindName("PART_Grid_Mouse_Drag", this) as ContentControl;

            _svDefault = Template.FindName("PART_ScrollView_Default", this) as ScrollViewer;

            grid_mark = Template.FindName("PART_Grid_Mark", this) as Grid;

            vb = Template.FindName("PART_ViewBox_Default", this) as Viewbox;

            rootGrid = Template.FindName("PART_Grid_Root", this) as Grid;

            mask = Template.FindName("PART_MarkCanvas_Mark", this) as MaskCanvas;

            controlmask = Template.FindName("PART_ContentControl_Mark", this) as ContentControl;

            popup = Template.FindName("PART_Grid_Popup", this) as Grid;

            BigBox = Template.FindName("PART_Canvas_BigBox", this) as Canvas;

            bigImg = Template.FindName("PART_Image_Big", this) as Image;

            bigrect = Template.FindName("PART_RectangleGeometry_Big", this) as RectangleGeometry;

            grid_all = Template.FindName("PART_Grid_All", this) as Grid;

            MoveRect = Template.FindName("PART_Ecllipse_Move", this) as Ellipse;

            _dynamic = Template.FindName("PART_DynamicShape_Draw", this) as DynamicShape;

            //  Do :初始化宽度高度
            this.InitWidthHeight();

            //  Do :初始化设置平铺
            this.SetFullImage();

            this.NoticeMessaged += (m, n) => Debug.WriteLine(this.Message);

            this.behaviors.ForEach(l => l.RegisterBehavior());
        }
        private static void PenTypeChanged(DependencyObject d,
                                           DependencyPropertyChangedEventArgs e)
        {
            InkCanvas ink = d as InkCanvas;

            if (ink == null)
            {
                return;
            }

            InkDrawingAttributes drawingAttributes = ink.InkPresenter.CopyDefaultDrawingAttributes();

            var penType = e.NewValue as PenType?;

            if (penType == null)
            {
                return;
            }

            switch (penType)
            {
            case PenType.Ballpoint:
                drawingAttributes.PenTip            = PenTipShape.Circle;
                drawingAttributes.DrawAsHighlighter = false;
                drawingAttributes.PenTipTransform   = System.Numerics.Matrix3x2.Identity;
                break;

            case PenType.Calligraphy:
                drawingAttributes.PenTip            = PenTipShape.Rectangle;
                drawingAttributes.DrawAsHighlighter = true;
                drawingAttributes.PenTipTransform   = System.Numerics.Matrix3x2.Identity;
                break;

            case PenType.Highlighter:
                drawingAttributes.PenTip            = PenTipShape.Rectangle;
                drawingAttributes.DrawAsHighlighter = false;

                // Set a 45 degree rotation on the pen tip
                double radians = 45.0 * Math.PI / 180;
                drawingAttributes.PenTipTransform = System.Numerics.Matrix3x2.CreateRotation((float)radians);
                break;
            }

            ink.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
        }
Beispiel #32
0
        /// <summary>
        /// Save InkCanvas strokes to .ink File
        /// </summary>
        /// <param name="inkCanvas">InkCanvas Object</param>
        /// <param name="location">PickerLocationId</param>
        /// <returns>Success or not</returns>
        public static async Task <Response> SaveToInkFile(InkCanvas inkCanvas, PickerLocationId location)
        {
            IRandomAccessStream stream = new InMemoryRandomAccessStream();

            var strokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();

            if (strokes.Any())
            {
                await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);

                var picker = new FileSavePicker
                {
                    SuggestedStartLocation = location
                };
                picker.FileTypeChoices.Add("INK files", new List <string> {
                    ".ink"
                });
                var file = await picker.PickSaveFileAsync();

                if (file == null)
                {
                    return(new Response
                    {
                        IsSuccess = false,
                        Message = $"{nameof(file)} is null"
                    });
                }

                CachedFileManager.DeferUpdates(file);
                var bt = await Utils.ConvertImagetoByte(stream);

                await FileIO.WriteBytesAsync(file, bt);

                await CachedFileManager.CompleteUpdatesAsync(file);

                return(new Response
                {
                    IsSuccess = true
                });
            }
            return(new Response
            {
                IsSuccess = false
            });
        }
Beispiel #33
0
        void SetZoom(double zoom)
        {
            MainInkCanvas.Width = zoom * 1000;
            var scale = pdf.scale;

            double ver_offset = scrollViewer.VerticalOffset;
            double view_h     = scrollViewer.ViewportHeight;

            double ra = (ver_offset + view_h / 2) / scrollViewer.ExtentHeight;

            double top = 0;

            for (int i = 0; i < pdf.pages.Count; i++)
            {
                var img  = GetImageWithPage(i);
                var page = pdf.pages[i];
                img.Top.Width  = zoom * scale * page.width;
                img.Top.Height = zoom * scale * page.height / 2;
                page.Top       = top;
                InkCanvas.SetTop(img.Top, top);
                top += zoom * scale * page.height / 2;
                img.Bottom.Width  = zoom * scale * page.width;
                img.Bottom.Height = zoom * scale * page.height / 2;
                InkCanvas.SetTop(img.Bottom, top);
                top += zoom * scale * page.height / 2;

                if (Math.Abs(pdf.last_render_zoom - zoom) >= 0.4)
                {
                    pdf.dirt = true;
                }
            }
            var ver_offset_new = top * ra - view_h / 2;

            scrollViewer.ScrollToVerticalOffset(ver_offset_new);
            MainInkCanvas.Height = top;
            var ma = new System.Windows.Media.Matrix();

            ma.ScaleAt(1 / render_zoom, 1 / render_zoom, 0, 0);
            //ma.Translate(-render_zoom / 2 * 1000, 0);
            ma.ScaleAt(zoom, zoom, 0, 0);
            MainInkCanvas.Strokes.Transform(ma, false);

            render_zoom = zoom;
            CheckInView(ver_offset_new, view_h);
        }
Beispiel #34
0
        /// <summary>
        /// Save InkCanvas strokes to .ink File
        /// </summary>
        /// <param name="inkCanvas">InkCanvas Object</param>
        /// <param name="location">PickerLocationId</param>
        /// <returns>Success or not</returns>
        public static async Task<Response> SaveToInkFile(InkCanvas inkCanvas, PickerLocationId location)
        {
            IRandomAccessStream stream = new InMemoryRandomAccessStream();

            var strokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();
            if (strokes.Any())
            {
                await inkCanvas.InkPresenter.StrokeContainer.SaveAsync(stream);

                var picker = new FileSavePicker
                {

                    SuggestedStartLocation = location
                };
                picker.FileTypeChoices.Add("INK files", new List<string> { ".ink" });
                var file = await picker.PickSaveFileAsync();
                if (file == null)
                {
                    return new Response
                    {
                        IsSuccess = false,
                        Message = $"{nameof(file)} is null"
                    };
                }

                CachedFileManager.DeferUpdates(file);
                var bt = await Utils.ConvertImagetoByte(stream);
                await FileIO.WriteBytesAsync(file, bt);
                await CachedFileManager.CompleteUpdatesAsync(file);

                return new Response
                {
                    IsSuccess = true
                };
            }
            return new Response
            {
                IsSuccess = false
            };
        }
        private static async Task SaveScreenshotInternal(StorageFile file, Panel parent, InkCanvas inkCanvas = null, List<FrameworkElement> excludedElements = null)
        {
            var strokeCanvas = new Canvas() { Name = _strokeCanvasName, Background = new SolidColorBrush(Colors.Transparent) };
            if (inkCanvas != null)
            {
                // add all inkCanvas strokes as children of the parent panel,
                // allowing us to save those with the RenderTargetBitmap
                RenderAllStrokes(inkCanvas, strokeCanvas);
                parent.Children.Add(strokeCanvas);
            }

            if (excludedElements != null)
            {
                foreach (FrameworkElement element in excludedElements)
                {
                    element.Visibility = Visibility.Collapsed;
                }
            }

            await SaveToFileAsync(parent, file);

            if (inkCanvas != null)
            {
                // HACK: there's an appearant bug in InkCanvas causing strokes to disappear after the rendering
                // we need to ensure the inkcanvas is updated.
                inkCanvas.Width += 1;
                inkCanvas.Width -= 1;

                parent.Children.Remove(strokeCanvas);
            }

            if (excludedElements != null)
            {
                foreach (FrameworkElement element in excludedElements)
                {
                    element.Visibility = Visibility.Visible;
                }
            }
        }
Beispiel #36
0
        private void LoadInkCanvas(int pageNumber)
        {
            Grid grid = (Grid)this.imagePanel.Children[pageNumber - 1];
            if (grid == null)
            {
                AppEventSource.Log.Warn("ViewerPage: Grid container for page " + pageNumber.ToString() + " not found.");
                return;
            }
            // Update the grid size to match the image size
            Image image = (Image)this.imagePanel.FindName(PREFIX_PAGE + pageNumber.ToString());
            grid.Width = image.ActualWidth;
            grid.Height = image.ActualHeight;
            // Find existing ink canvas
            InkCanvas inkCanvas = (InkCanvas)grid.FindName(PREFIX_CANVAS + pageNumber.ToString());
            // If an ink canvas does not exist, add a new one
            if (inkCanvas == null)
            {
                Binding bindingHeight = new Binding();
                bindingHeight.Mode = BindingMode.OneWay;
                bindingHeight.Path = new PropertyPath("ActualHeight");
                bindingHeight.Source = image;
                Binding bindingWidth = new Binding();
                bindingWidth.Mode = BindingMode.OneWay;
                bindingWidth.Path = new PropertyPath("ActualWidth");
                bindingWidth.Source = image;
                // Add ink canvas
                if (inkCanvasStack.Count > 0)
                    inkCanvas = inkCanvasStack.Pop();
                else inkCanvas = new InkCanvas();
                inkCanvas.Name = PREFIX_CANVAS + pageNumber.ToString();
                inkCanvas.InkPresenter.InputDeviceTypes = inkingPreference.drawingDevice;
                inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
                inkCanvas.InkPresenter.StrokesCollected += InkPresenter_StrokesCollected;
                inkCanvas.InkPresenter.StrokesErased += InkPresenter_StrokesErased;
                inkCanvas.InkPresenter.InputProcessingConfiguration.Mode = this.inkProcessMode;
                inkCanvas.SetBinding(HeightProperty, bindingHeight);
                inkCanvas.SetBinding(WidthProperty, bindingWidth);

                this.inkCanvasList.Add(pageNumber);
                // Load inking if exist
                InkStrokeContainer inkStrokesContainer = inkManager.loadInking(pageNumber);
                if (inkStrokesContainer != null)
                    inkCanvas.InkPresenter.StrokeContainer = inkStrokesContainer;
                // Add ink canvas page
                grid.Children.Add(inkCanvas);
                
            }
        }
        private static void RenderAllStrokes(InkCanvas canvas, Panel parent)
        {
            // Get the InkStroke objects.
            IReadOnlyList<InkStroke> inkStrokes = canvas.InkPresenter.StrokeContainer.GetStrokes();

            List<Windows.UI.Xaml.Shapes.Path> retVal = new List<Windows.UI.Xaml.Shapes.Path>();

            // Process each stroke.
            foreach (InkStroke inkStroke in inkStrokes)
            {
                PathGeometry pathGeometry = new PathGeometry();
                PathFigureCollection pathFigures = new PathFigureCollection();
                PathFigure pathFigure = new PathFigure();
                PathSegmentCollection pathSegments = new PathSegmentCollection();

                // Create a path and define its attributes.
                Windows.UI.Xaml.Shapes.Path path = new Windows.UI.Xaml.Shapes.Path();
                path.Stroke = new SolidColorBrush(inkStroke.DrawingAttributes.Color);
                path.StrokeThickness = inkStroke.DrawingAttributes.Size.Height;
                if (inkStroke.DrawingAttributes.DrawAsHighlighter)
                {
                    path.Opacity = .4d;
                }

                // Get the stroke segments.
                IReadOnlyList<InkStrokeRenderingSegment> segments;
                segments = inkStroke.GetRenderingSegments();

                // Process each stroke segment.
                bool first = true;
                foreach (InkStrokeRenderingSegment segment in segments)
                {
                    // The first segment is the starting point for the path.
                    if (first)
                    {
                        pathFigure.StartPoint = segment.BezierControlPoint1;
                        first = false;
                    }

                    // Copy each ink segment into a bezier segment.
                    BezierSegment bezSegment = new BezierSegment();
                    bezSegment.Point1 = segment.BezierControlPoint1;
                    bezSegment.Point2 = segment.BezierControlPoint2;
                    bezSegment.Point3 = segment.Position;

                    // Add the bezier segment to the path.
                    pathSegments.Add(bezSegment);
                }

                // Build the path geometerty object.
                pathFigure.Segments = pathSegments;
                pathFigures.Add(pathFigure);
                pathGeometry.Figures = pathFigures;

                // Assign the path geometry object as the path data.
                path.Data = pathGeometry;

                // Render the path by adding it as a child of the Canvas object.
                parent.Children.Add(path);
            }
        }
        public static async Task SaveScreenshotAsync(this Panel parent, InkCanvas inkCanvas = null, List<FrameworkElement> excludedElements = null)
        {
            var file = await PickSaveImageAsync();

            await SaveScreenshotInternal(file, parent, inkCanvas, excludedElements);
        }
Beispiel #39
0
 public Task ExportPageImage(int pageNumber, InkCanvas inkCanvas, StorageFile saveFile)
 {
     return msPdf.ExportPageImage(pageNumber, inkCanvas, saveFile);
 }
Beispiel #40
0
        protected override void OnApplyTemplate()
        {
            try
            {
                container = GetTemplateChild(PART_ROOT_NAME) as Grid;
                inker = GetTemplateChild(PART_INKER_NAME) as InkCanvas;
                if (container != null && inker != null)
                {
                    container.Visibility = Visibility.Visible;
                    InitializeInker();

                    root = VisualTreeHelperEx.FindRoot(container, false);
                    contentPresenter = VisualTreeHelperEx.FindRoot(container, true);

                    contentPresenter.PointerEntered += Element_PointerEntered;
                    contentPresenter.PointerExited += Element_PointerExited;
                    contentPresenter.PointerCanceled += Element_PointerCanceled;
                    contentPresenter.PointerReleased += Element_PointerCanceled;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }
        }
Beispiel #41
0
        protected override void OnApplyTemplate()
        {
            container = this.GetTemplateChild(ContainerName) as Grid;
            textBox = this.GetTemplateChild(TextBoxName) as TextBox;
            inkCanvas = this.GetTemplateChild(InkCanvasName) as InkCanvas;
            inkBorder = this.GetTemplateChild(InkBorderName) as Border;
            inkWindow = this.GetTemplateChild(InkWindowName) as Popup;

            inkRecognizerContainer = new InkRecognizerContainer();
            recognizers = inkRecognizerContainer.GetRecognizers();

            // Set the text services so we can query when language changes
            textServiceManager = CoreTextServicesManager.GetForCurrentView();
            textServiceManager.InputLanguageChanged += TextServiceManager_InputLanguageChanged;

            SetDefaultRecognizerByCurrentInputMethodLanguageTag();

            // Create a timer that expires after 1 second
            recognitionTimer = new DispatcherTimer();
            recognitionTimer.Interval = new TimeSpan(0, 0, 1);
            recognitionTimer.Tick += RecoTimer_Tick;

            pointerTimer = new DispatcherTimer();
            pointerTimer.Interval = new TimeSpan(0, 0, 2);
            pointerTimer.Tick += PointerTimer_Tick;

            textBox.PointerEntered += TextBox_PointerEntered;
            textBox.AddHandler(PointerPressedEvent, new PointerEventHandler(TextBox_PointerPressed), true);
            textBox.SelectionChanged += TextBox_SelectionChanged;

            inkCanvas.PointerEntered += InkCanvas_PointerEntered;
            inkCanvas.InkPresenter.StrokesCollected += InkCanvas_StrokesCollected;
            inkCanvas.InkPresenter.StrokeInput.StrokeStarted += InkCanvas_StrokeStarted;
            inkCanvas.InkPresenter.StrokesErased += InkPresenter_StrokesErased;
            
            // Initialize drawing attributes. These are used in inking mode.
            InkDrawingAttributes drawingAttributes = new InkDrawingAttributes();
            drawingAttributes.Color = InkColor;
            double penSize = PenSize;
            drawingAttributes.Size = new Windows.Foundation.Size(penSize, penSize);
            drawingAttributes.IgnorePressure = false;
            drawingAttributes.FitToCurve = true;

            // Initialize the InkCanvas
            inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
            inkCanvas.InkPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Pen;

            //InputPane inputPane = InputPane.GetForCurrentView();
            //inputPane.Showing += InputPane_Showing;

            this.SizeChanged += InkTextBox_SizeChanged;

            enableText();
            base.OnApplyTemplate();
        }
Beispiel #42
0
 /// <summary>
 /// Load strokes from .ink file to InkCanvas
 /// </summary>
 /// <param name="inkCanvas">InkCanvas Object</param>
 /// <param name="location">PickerLocationId</param>
 /// <returns>Task</returns>
 public static async Task LoadInkFile(InkCanvas inkCanvas, PickerLocationId location)
 {
     var picker = new FileOpenPicker
     {
         SuggestedStartLocation = location
     };
     picker.FileTypeFilter.Add(".ink");
     var pickedFile = await picker.PickSingleFileAsync();
     if (pickedFile != null)
     {
         var file = await pickedFile.OpenReadAsync();
         await inkCanvas.InkPresenter.StrokeContainer.LoadAsync(file);
     }
 }
Beispiel #43
0
        /// <summary>
        /// Save a rendered pdf page with inking to png file.
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="saveFile"></param>
        /// <returns></returns>
        public async Task ExportPageImage(int pageNumber, InkCanvas inkCanvas, StorageFile saveFile)
        {
            CanvasDevice device = CanvasDevice.GetSharedDevice();
            CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)inkCanvas.ActualWidth, (int)inkCanvas.ActualHeight, 96 * 2);

            // Render pdf page
            InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
            PdfPage page = PdfDoc.GetPage(Convert.ToUInt32(pageNumber - 1));
            PdfPageRenderOptions options = new PdfPageRenderOptions();
            options.DestinationWidth = (uint)inkCanvas.ActualWidth * 2;
            await page.RenderToStreamAsync(stream, options);
            CanvasBitmap bitmap = await CanvasBitmap.LoadAsync(device, stream, 96 * 2);
            // Draw image with ink
            using (var ds = renderTarget.CreateDrawingSession())
            {
                ds.Clear(Windows.UI.Colors.White);
                ds.DrawImage(bitmap);
                ds.DrawInk(inkCanvas.InkPresenter.StrokeContainer.GetStrokes());
            }

            // Encode the image to the selected file on disk
            using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
                await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f);
        }
Beispiel #44
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            object obj = e.Parameter;
            if (null != obj)
            {
                string path = obj as string;
                imgPath = path;
                int index = 0;
                while (index >= 0)
                {
                    index = path.IndexOf('\\');
                    if (index >= 0)
                    {
                        path = path.Substring(index + 1);
                    }
                }
                index = path.IndexOf('.');
                if(index < 0)
                {
                    imageName = path;
                }
                else
                {
                    imageName = path.Substring(0, index);
                }
                
                
                StorageFile file = await StorageFile.GetFileFromPathAsync(imgPath);
                using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
                {
                    BitmapImage image = new BitmapImage();
                    image.SetSource(fileStream);
                    source = image;
                }
                InkCanvas inkCanvas = new InkCanvas();
                inkCanvas.InkPresenter.StrokeContainer.Clear();
                var stream = await file.OpenSequentialReadAsync();
                if (null != stream)
                {
                    try
                    {
                        await inkCanvas.InkPresenter.StrokeContainer.LoadAsync(stream);
                        if (inkCanvas.InkPresenter.StrokeContainer.GetStrokes().Count != 0)
                        {
                            isInkPic = true;
                        }
                    }
                    catch (Exception ex)
                    {
#if DEBUG
                        System.Diagnostics.Debug.WriteLine(ex.Message);
#endif
                        isInkPic = false;
                    }
                }
            }
            if (null != source)
            {
                ResourceDictionary dic = Application.Current.Resources;
                IList<ResourceDictionary> dics = dic.MergedDictionaries;
                ResourceDictionary resource = null;
                foreach(var item in dics)
                {
                    if(item.Source.AbsolutePath.Contains("/Files/Styles/Styles.xaml"))
                    {
                        resource = item;
                        break;
                    }

                }
                object style = null;
                if(null != resource)
                {
                                       
                    resource.TryGetValue("CheckBoxStyle", out style);
                }               

                ImageBrush brush = new ImageBrush();
                brush.ImageSource = source;
                //item 1
                GoodsPanel panel1 = new GoodsPanel();
                panel1.PictureWith = PicWidth;
                CheckBox check1 = new CheckBox();
                //check1.SetValue(StyleProperty,);
                check1.Checked += CheckBox_Checked;
                check1.Unchecked += CheckBox_Unchecked;
                if((style as Style) != null)
                {
                    check1.SetValue(StyleProperty, style);
                }
                panel1.Check = check1;
                panel1.PictureBrush = brush;
                panel1.GoodsName = "白杯子";
                panel1.Price = "¥35";
                panel1.PicturePath = imgPath;
                goodsPanels.Add(0,panel1);
                panel1.SetValue(RelativePanel.AlignLeftWithPanelProperty,true);
                panel1.SetValue(RelativePanel.AlignTopWithPanelProperty,true);
                goodsPanel.Children.Add(panel1);

                //item 2
                GoodsPanel panel2 = new GoodsPanel();
                panel2.PictureWith = PicWidth;
                CheckBox check2 = new CheckBox();
                //check1.SetValue(StyleProperty,);
                check2.Checked += CheckBox_Checked;
                check2.Unchecked += CheckBox_Unchecked;
                panel2.Check = check2;
                if ((style as Style) != null)
                {
                    check2.SetValue(StyleProperty, style);
                }
                panel2.PictureBrush = brush;
                panel2.GoodsName = "黑杯子";
                panel2.Price = "¥35";
                panel2.PicturePath = imgPath;
                goodsPanels.Add(1, panel2);
                panel2.SetValue(RelativePanel.RightOfProperty, panel1.Name);
                panel2.SetValue(RelativePanel.AlignTopWithPanelProperty, true);
                goodsPanel.Children.Add(panel2);

                //item 3
                GoodsPanel panel3 = new GoodsPanel();
                panel3.PictureWith = PicWidth;
                CheckBox check3 = new CheckBox();
                //check1.SetValue(StyleProperty,);
                check3.Checked += CheckBox_Checked;
                check3.Unchecked += CheckBox_Unchecked;
                panel3.Check = check3;
                if ((style as Style) != null)
                {
                    check3.SetValue(StyleProperty, style);
                }
                panel3.PictureBrush = brush;
                panel3.GoodsName = "白T恤";
                panel3.Price = "¥86";
                panel3.PicturePath = imgPath;
                goodsPanels.Add(2, panel3);
                panel3.SetValue(RelativePanel.RightOfProperty, panel2.Name);
                panel3.SetValue(RelativePanel.AlignTopWithPanelProperty, true);
                goodsPanel.Children.Add(panel3);

                //item 4
                GoodsPanel panel4 = new GoodsPanel();
                panel4.PictureWith = PicWidth;
                CheckBox check4 = new CheckBox();
                //check1.SetValue(StyleProperty,);
                check4.Checked += CheckBox_Checked;
                check4.Unchecked += CheckBox_Unchecked;
                panel4.Check = check4;
                if ((style as Style) != null)
                {
                    check4.SetValue(StyleProperty, style);
                }
                panel4.PictureBrush = brush;
                panel4.GoodsName = "黑T恤";
                panel4.Price = "¥86";
                panel4.PicturePath = imgPath;
                goodsPanels.Add(3, panel4);
                panel4.SetValue(RelativePanel.RightOfProperty, panel3.Name);
                panel4.SetValue(RelativePanel.AlignTopWithPanelProperty, true);
                goodsPanel.Children.Add(panel4);
                ResetPicturePanelPositon();
            }
        }
        private void Initialize()
        {
            if (!_initialized)
            {
                _inkCanvas = new InkCanvas();
                _inkToolbar = new InkToolbarControl(this);

                InkDrawingAttributes drawingAttributes = new InkDrawingAttributes
                {
                    Color = PenColor,
                    Size = PenSize,
                    IgnorePressure = false,
                    FitToCurve = true,
                };

                _inkCanvas.InkPresenter.UpdateDefaultDrawingAttributes(drawingAttributes);
                _inkCanvas.InkPresenter.InputDeviceTypes = Windows.UI.Core.CoreInputDeviceTypes.Mouse | Windows.UI.Core.CoreInputDeviceTypes.Pen | Windows.UI.Core.CoreInputDeviceTypes.Touch;
                
                Panel parent = (Panel)AssociatedObject;
                parent.Children.Add(_inkCanvas);
                parent.Children.Add(_inkToolbar);

                // The canvas utilized for adding annotations. the background is set to null to ensure hittesting on the inkcanvas works.
                _annotationCanvas = new Canvas { Background = null };
                parent.Children.Add(_annotationCanvas);
                parent.Tapped += Parent_Tapped;

                _inkCanvas.InkPresenter.IsInputEnabled = false;
                _inkCanvas.Width = 0;
                _inkCanvas.Height = 0;
                _inkCanvas.Visibility = Visibility.Collapsed;
                _inkToolbar.Visibility = Visibility.Collapsed;

                _initialized = true;

                ChangeDrawTool(SelectedTool);
            }
        }