private void tcpipServer_OnCalibrationFeedbackPoint(long time, int packagenumber, int targetX, int targetY,
                                                            int gazeX, int gazeY, float distance, int acquisitionTime)
        {
            CalibrationWindow.Instance.Dispatcher.Invoke
            (
                DispatcherPriority.ApplicationIdle,
                new Action
                (
                    delegate
            {
                //pass info from the dedicated interface to the tracker class
                var target = new System.Drawing.Point(targetX, targetY);
                var gaze   = new GTPoint(gazeX, gazeY);
                //tracker.SaveRecalibInfo(time, packagenumber, target, gaze);

                /* outputting the data in a local class */
                string del = " ";
                string msg = DateTime.Now.Ticks + del
                             + time + del
                             + packagenumber + del
                             + targetX + del
                             + targetX + del
                             + gazeX + del
                             + gazeY + del
                             + distance + del
                             + acquisitionTime;
                Output.Instance.appendToFile(msg);
            }
                )
            );
        }
Esempio n. 2
0
        /// <summary>
        /// Call back function for take snapshot command dependency property,
        /// when no video device source selected show appropriate message
        /// or message currently display in user-control based on user input.
        /// </summary>
        /// <exception cref="InvalidOperationException">Wraps and throws <see cref="InvalidOperationException"/> when any exception is thrown from this method.</exception>
        public void TakeSnapshotCallback()
        {
            try
            {
                var playerPoint = new System.Drawing.Point();

                //// Get the position of the source video device player.
                if (string.IsNullOrWhiteSpace(VideoSourceId))
                {
                    var noVideoDeviceSourcePoint = NoVideoSourceGrid.PointToScreen(new Point(0, 0));
                    playerPoint.X = (int)noVideoDeviceSourcePoint.X;
                    playerPoint.Y = (int)noVideoDeviceSourcePoint.Y;
                }
                else
                {
                    playerPoint =
                        VideoSourcePlayer.PointToScreen(new System.Drawing.Point(VideoSourcePlayer.ClientRectangle.X,
                                                                                 VideoSourcePlayer.ClientRectangle.Y));
                }

                if (double.IsNaN(VideoPreviewWidth) || double.IsNaN(VideoPreviewHeight))
                {
                    using (
                        var bitmap = new Bitmap((int)VideoSourceWindowsFormsHost.ActualWidth,
                                                (int)VideoSourceWindowsFormsHost.ActualHeight))
                    {
                        using (var graphicsFromImage = Graphics.FromImage(bitmap))
                        {
                            graphicsFromImage.CopyFromScreen(playerPoint,
                                                             System.Drawing.Point.Empty,
                                                             new System.Drawing.Size((int)VideoSourceWindowsFormsHost.ActualWidth,
                                                                                     (int)VideoSourceWindowsFormsHost.ActualHeight));
                        }

                        SnapshotBitmap = new Bitmap(bitmap);
                    }
                }
                else
                {
                    using (var bitmap = new Bitmap((int)VideoPreviewWidth, (int)VideoPreviewHeight))
                    {
                        using (var graphicsFromImage = Graphics.FromImage(bitmap))
                        {
                            graphicsFromImage.CopyFromScreen(playerPoint,
                                                             System.Drawing.Point.Empty,
                                                             new System.Drawing.Size((int)VideoPreviewWidth, (int)VideoPreviewHeight));
                        }

                        SnapshotBitmap = new Bitmap(bitmap);
                    }
                }
            }
            catch (Exception exception)
            {
                throw new InvalidOperationException(
                          "Error occurred while trying to take snapshot from currently selected source video device",
                          exception);
            }
        }
Esempio n. 3
0
        private System.Drawing.Point vectorToPoint(Vector vector)
        {
            int translatedEvaderCoordinateX = (int)Math.Round(vector.X);
            int translatedEvaderCoordinateY = (int)Math.Round(vector.Y);

            System.Drawing.Point point = new System.Drawing.Point(translatedEvaderCoordinateX, translatedEvaderCoordinateY);
            return(point);
        }
 protected virtual IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
 {
     switch (msg)
     {
     case WmNchittest:
         var mousePoint = new System.Drawing.Point(lParam.ToInt32() & 0xFFFF, lParam.ToInt32() >> 16);
         if (mousePoint.Y - Top <= AgWidth &&
             mousePoint.X - Left <= AgWidth)
         {
             handled = true;
             return(new IntPtr((int)HitTest.Httopleft));
         }
         else if (ActualHeight + Top - mousePoint.Y <= AgWidth &&
                  mousePoint.X - Left <= AgWidth)
         {
             handled = true;
             return(new IntPtr((int)HitTest.Htbottomleft));
         }
         else if (mousePoint.Y - Top <= AgWidth &&
                  ActualWidth + Left - mousePoint.X <= AgWidth)
         {
             handled = true;
             return(new IntPtr((int)HitTest.Httopright));
         }
         else if (ActualWidth + Left - mousePoint.X <= AgWidth &&
                  ActualHeight + Top - mousePoint.Y <= AgWidth)
         {
             handled = true;
             return(new IntPtr((int)HitTest.Htbottomright));
         }
         else if (mousePoint.X - Left <= BThickness)
         {
             handled = true;
             return(new IntPtr((int)HitTest.Htleft));
         }
         else if (ActualWidth + Left - mousePoint.X <= BThickness)
         {
             handled = true;
             return(new IntPtr((int)HitTest.Htright));
         }
         else if (mousePoint.Y - Top <= BThickness)
         {
             handled = true;
             return(new IntPtr((int)HitTest.Httop));
         }
         else if (ActualHeight + Top - mousePoint.Y <= BThickness)
         {
             handled = true;
             return(new IntPtr((int)HitTest.Htbottom));
         }
         else
         {
             handled = false;
             return(IntPtr.Zero);
         }
     }
     return(IntPtr.Zero);
 }
Esempio n. 5
0
        private void SyncTreatmentSensor()
        {
            var pos = new System.Drawing.Point(AppSettings.Default.TreatmentSensorX, AppSettings.Default.TreatmentSensorY);

            if (Controller?.Pipeline?.VideoInfo != null)
            {
                treatmentSensor.Position = Controller.ToCanvasCoordinates(pos);
            }
        }
Esempio n. 6
0
        public static WpfScreen GetScreenFrom(Point point)
        {
            var x = (int)Math.Round(point.X);
            var y = (int)Math.Round(point.Y);

            System.Drawing.Point drawingPoint = new System.Drawing.Point(x, y);
            var screen = Screen.FromPoint(drawingPoint);
            return new WpfScreen(screen);
        }
Esempio n. 7
0
        public static System.Drawing.Point CountMousePosition(IImage image, PointF pointRelativeToImage)
        {
            var imageHeight = image.Bitmap.Height;
            var imageWidth  = image.Bitmap.Width;
            var xMultiplier = 1920 / imageWidth; //TODO zmienić wartości nie na sztywno
            var yMultiplier = 1080 / imageHeight;
            var result      = new System.Drawing.Point(Convert.ToInt32(pointRelativeToImage.X * xMultiplier), Convert.ToInt32(pointRelativeToImage.Y * yMultiplier));

            return(result);
        }
Esempio n. 8
0
        public static WpfScreen GetScreenFrom(Point point)
        {
            var x = (int)Math.Round(point.X);
            var y = (int)Math.Round(point.Y);

            System.Drawing.Point drawingPoint = new System.Drawing.Point(x, y);
            var screen = Screen.FromPoint(drawingPoint);

            return(new WpfScreen(screen));
        }
Esempio n. 9
0
        public static ScreenService GetScreenFrom(Point point)
        {
            int x = (int)Math.Round(point.X);
            int y = (int)Math.Round(point.Y);

            // are x,y device-independent-pixels ??
            System.Drawing.Point drawingPoint = new System.Drawing.Point(x, y);
            Screen        screen    = System.Windows.Forms.Screen.FromPoint(drawingPoint);
            ScreenService wpfScreen = new ScreenService(screen);

            return(wpfScreen);
        }
Esempio n. 10
0
        public static WpfScreen GetScreenFrom(Point point)
        {
            int x = (int)Math.Round(point.X);
            int y = (int)Math.Round(point.Y);

            // are x,y device-independent-pixels ??
            System.Drawing.Point drawingPoint = new System.Drawing.Point(x, y);
            Screen screen = Screen.FromPoint(drawingPoint);
            WpfScreen wpfScreen = new WpfScreen(screen);

            return wpfScreen;
        }
Esempio n. 11
0
        public static WpfScreen GetScreenFrom(Point point)
        {
            int x = (int)Math.Round(point.X);
            int y = (int)Math.Round(point.Y);

            // are x,y device-independent-pixels ??
            System.Drawing.Point drawingPoint = new System.Drawing.Point(x, y);
            Screen    screen    = Screen.FromPoint(drawingPoint);
            WpfScreen wpfScreen = new WpfScreen(screen);

            return(wpfScreen);
        }
Esempio n. 12
0
        private void SyncAntennaSensor()
        {
            var headPos = new System.Drawing.Point(AppSettings.Default.HeadX, AppSettings.Default.HeadY);
            var dim     = AppSettings.Default.HeadScale * 100 * CanvasScale;

            if (Controller?.Pipeline?.VideoInfo != null)
            {
                antennaSensor.Position   = Controller.ToCanvasCoordinates(headPos);
                antennaSensor.Dimensions = new Point(dim, dim);
            }

            Controller.RefreshMostRecentFrame();
        }
Esempio n. 13
0
 private static void DrawOutIndices(Bitmap bitmap, MinAndMaxIndices[] minMaxXIndices, Color color)
 {
     using (var g = Graphics.FromImage(bitmap))
     {
         var sourcePen = new Pen(color);
         for (var index = 0; index < minMaxXIndices.Length - 1; index++)
         {
             var p1Draw = new System.Drawing.Point(minMaxXIndices[index].Max, index);
             var p2Draw = new System.Drawing.Point(minMaxXIndices[index + 1].Max, (index + 1));
             g.DrawLine(sourcePen, p1Draw, p2Draw);
         }
     }
 }
Esempio n. 14
0
 private static void DrawOutPoints(Image bitmap, Color color, IList <Point> points)
 {
     using (var g = Graphics.FromImage(bitmap))
     {
         var sourcePen = new Pen(color);
         for (var index = 0; index < points.Count - 1; index++)
         {
             var p1     = points[index];
             var p2     = points[index + 1];
             var p1Draw = new System.Drawing.Point((int)p1.X, (int)p1.Y);
             var p2Draw = new System.Drawing.Point((int)p2.X, (int)p2.Y);
             g.DrawLine(sourcePen, p1Draw, p2Draw);
         }
     }
 }
Esempio n. 15
0
        /// <inheritdoc/>
        public async Task <bool> StartGame()
        {
            EnsureNotDestroyed();
            if (IsDestroying)
            {
                throw new InvalidOperationException("This controller is beeing disposed.");
            }
            // Run the game in a separate thread (create Form and run)
            sceneGameThread.Start();
            // Wait for the game to start
            await gameStartedTaskSource.Task;

            GameForm.MouseDown += (sender, e) => lastClickPosition = Control.MousePosition;
            // Initialize the WPF GameEngineHwndHost on this thread
            GameForm.Host = new GameEngineHost(windowHandle);

            // TODO: we could check if the game fails to create.
            return(true);
        }
        internal Point GetPasteReferenceLocation()
        {
            System.Drawing.Point mouse = System.Windows.Forms.Cursor.Position;
            Point mousePoint           = new Point(mouse.X, mouse.Y);
            Point viewPoint            = PointFromScreen(mousePoint);

            Point viewMax     = new Point(ActualWidth, ActualHeight);
            Point canvasPoint = NodeCanvas.PointFromScreen(mousePoint);

            if (viewPoint.X > 0 && viewPoint.Y > 0 && viewPoint.X < viewMax.X && viewPoint.Y < viewMax.Y)
            {
                return(canvasPoint);
            }

            // little hack here as nodes are pasted at their TopLeft Corner we offset the MaxBottomRight location so nodes are not pasted entirely offscreen
            double viewX = Math.Max(Math.Min(viewMax.X - 100, viewPoint.X), 0);
            double viewY = Math.Max(Math.Min(viewMax.Y - 100, viewPoint.Y), 0);

            GeneralTransform toCanvas = NodeGraphOuter.TransformToDescendant(NodeCanvas);

            return(toCanvas.Transform(new Point(viewX, viewY)));
        }
Esempio n. 17
0
        private void LoadFromSettings()
        {
            ValidateSettings();

            var headPos = new System.Drawing.Point(AppSettings.Default.HeadX, AppSettings.Default.HeadY);
            var dim     = AppSettings.Default.HeadScale * 100 * CanvasScale;

            sliderX.Max       = AppSettings.Default.MaxHeadX;
            sliderX.IsEnabled = true;
            sliderX.LoadFromSettings();

            sliderY.Max = AppSettings.Default.MaxHeadY;
            sliderY.LoadFromSettings();
            sliderY.IsEnabled = true;

            sliderScale.Max = AppSettings.Default.MaxHeadScale;
            sliderScale.Min = 0.1;
            sliderScale.LoadFromSettings();
            sliderScale.IsEnabled = true;

            sliderAngle.Max = 360;
            sliderAngle.Min = -360;
            sliderAngle.LoadFromSettings();
            sliderAngle.IsEnabled = true;

            sliderTreatX.Max = AppSettings.Default.MaxTreatX;
            sliderTreatX.LoadFromSettings();
            sliderTreatX.IsEnabled = true;

            sliderTreatY.Max = AppSettings.Default.MaxTreatY;
            sliderTreatY.LoadFromSettings();
            sliderTreatY.IsEnabled = true;

            chkShowFilterPoints.IsChecked = AppSettings.Default.ShowModel;
            txtVideoLabel.Text            = AppSettings.Default.VideoLabel;
            txtVideoLabelColumn.Text      = AppSettings.Default.VideoLabelColumn;
        }
Esempio n. 18
0
        private void exportButton_Click(object sender, RoutedEventArgs e)
        {
            var topLeftCorner   = Browser.PointToScreen(new Point(0, 0));
            var topLeftGdiPoint = new System.Drawing.Point((int)topLeftCorner.X, (int)topLeftCorner.Y);
            var size            = new Size((int)Browser.ActualWidth, (int)Browser.ActualHeight);

            var screenShot = new Bitmap((int)Browser.ActualWidth, (int)Browser.ActualHeight);

            using (var graphics = Graphics.FromImage(screenShot))
            {
                graphics.CopyFromScreen(topLeftGdiPoint, new System.Drawing.Point(),
                                        size, CopyPixelOperation.SourceCopy);
            }
            var saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "Png Image|*.png";
            saveFileDialog1.Title  = "Save an Image File";
            saveFileDialog1.ShowDialog();
            if (saveFileDialog1.FileName != "")
            {
                screenShot.Save(saveFileDialog1.FileName, ImageFormat.Png);
                MessageBox.Show("Saved image succesfully to: " + saveFileDialog1.FileName);
            }
        }
Esempio n. 19
0
		public System.Drawing.PointF WorldToTilePos(double lon, double lat, int zoom)
			{
			System.Drawing.PointF p = new System.Drawing.Point();
			p.X = (float)((lon + 180.0) / 360.0 * (1 << zoom));
			p.Y = (float)((1.0 - Math.Log(Math.Tan(lat * Math.PI / 180.0) +
				1.0 / Math.Cos(lat * Math.PI / 180.0)) / Math.PI) / 2.0 * (1 << zoom));

			return p;
			}
        /// <summary>
        /// Call back function for take snapshot command dependency property,
        /// when no video device source selected show appropriate message
        /// or message currently display in user-control based on user input.
        /// </summary>
        /// <exception cref="InvalidOperationException">Wraps and throws <see cref="InvalidOperationException"/> when any exception is thrown from this method.</exception>
        public void TakeSnapshotCallback()
        {
            CalculateDpiFactors();
            try
            {
                var playerPoint = new Drawing.Point();
                //// Get the position of the source video device player.
                if (string.IsNullOrWhiteSpace(this.VideoSourceId))
                {
                    var noVideoDeviceSourcePoint = this.NoVideoSourceGrid.PointToScreen(new Point(0, 0));
                    playerPoint.X = (int)noVideoDeviceSourcePoint.X;
                    playerPoint.Y = (int)noVideoDeviceSourcePoint.Y;
                }
                else
                {
                    playerPoint = this.VideoSourcePlayer.PointToScreen(new Drawing.Point(this.VideoSourcePlayer.ClientRectangle.X, this.VideoSourcePlayer.ClientRectangle.Y));
                }
                if (double.IsNaN(this.VideoPreviewWidth) || double.IsNaN(this.VideoPreviewHeight))
                {                    
                    using (var bitmap = new Bitmap((int)(this.VideoSourceWindowsFormsHost.ActualWidth * thisDpiWidthFactor),
                                                   (int)(this.VideoSourceWindowsFormsHost.ActualHeight * thisDpiHeightFactor)))
                    {

                        using (var graphicsFromImage = Graphics.FromImage(bitmap))
                        {
                            graphicsFromImage.CopyFromScreen(playerPoint, Drawing.Point.Empty,
                                new Drawing.Size((int)(this.VideoSourceWindowsFormsHost.ActualWidth * thisDpiWidthFactor),
                                    (int)(this.VideoSourceWindowsFormsHost.ActualHeight * thisDpiHeightFactor)));
                        }
                        this.SnapshotBitmap = new Bitmap(bitmap);
                    }
                }
                else
                {
                    using (var bitmap = new Bitmap((int)this.VideoPreviewWidth, (int)this.VideoPreviewHeight))
                    {
                        using (var graphicsFromImage = Graphics.FromImage(bitmap))
                        {
                            graphicsFromImage.CopyFromScreen(playerPoint, Drawing.Point.Empty, new Drawing.Size((int)this.VideoPreviewWidth, (int)this.VideoPreviewHeight));
                        }
                        this.SnapshotBitmap = new Bitmap(bitmap);
                    }
                }
            }
            catch (Exception exception)
            {
                throw new InvalidOperationException("Error occurred while trying to take snapshot from currently selected source video device", exception);
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Changes the cursor for this control to show the coordinates
        /// </summary>
        /// <param name="uiElement"></param>
        private void SetCoordinatesOnCursor(FrameworkElement uiElement)
        {
            Point  coordinate = locked ? lockPoint : lastCoordinate;
            Cursor newCursor  = null;
            var    cursorFont = new Font("Arial", 8f);

            try
            {
                // Lets get the string to be printed
                string coordinateText = coordinate.X.ToString(xFormat) + "," + coordinate.Y.ToString(yFormat);
                // Calculate the rectangle required to draw the string
                SizeF textSize = GetTextSize(coordinateText, cursorFont);

                // ok, so here's the minimum 1/4 size of the bitmap we need, as the
                // Hotspot for the cursor will be in the centre of the bitmap.
                int minWidth  = 8 + (int)Math.Ceiling(textSize.Width);
                int minHeight = 8 + (int)Math.Ceiling(textSize.Height);

                // If the bitmap needs to be resized, then resize it, else just clear it
                if (cursorBitmap.Width < minWidth * 2 || cursorBitmap.Height < minHeight * 2)
                {
                    Bitmap oldBitmap = cursorBitmap;
                    cursorBitmap = new Bitmap(Math.Max(cursorBitmap.Width, minWidth * 2),
                                              Math.Max(cursorBitmap.Height, minHeight * 2));
                    oldBitmap.Dispose();
                }

                // Get the centre of the bitmap which will be the Hotspot
                var centre = new System.Drawing.Point(cursorBitmap.Width / 2, cursorBitmap.Height / 2);
                /// Calculate the text rectangle
                var textRectangle = new Rectangle(centre.X + 8, centre.Y + 8, minWidth - 8, minHeight - 8);

                int diff = (int)cursorPosition.X + textRectangle.Right / 2 - 3 - (int)uiElement.ActualWidth;

                if (diff > 0)
                {
                    textRectangle.Location = new System.Drawing.Point(textRectangle.Left - diff, textRectangle.Top);
                }

                // Draw the target symbol, and the coordinate text on the bitmap
                using (Graphics g = Graphics.FromImage(cursorBitmap))
                {
                    g.SmoothingMode = SmoothingMode.AntiAlias;
                    // This line causes a crash on laptops when you render a string
                    // g.CompositingMode = CompositingMode.SourceCopy;
                    g.Clear(Color.Transparent);

                    float targetX = centre.X;
                    float targetY = centre.Y;

                    float radius = 30;

                    if (!locked)
                    {
                        var blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 1.4f);
                        g.DrawEllipse(blackPen, targetX - radius * .5f, targetY - radius * .5f, radius, radius);
                        g.DrawLine(blackPen, targetX - radius * .8f, targetY, targetX - 2f, targetY);
                        g.DrawLine(blackPen, targetX + 2f, targetY, targetX + radius * .8f, targetY);
                        g.DrawLine(blackPen, targetX, targetY - radius * .8f, targetX, targetY - 2f);
                        g.DrawLine(blackPen, targetX, targetY + 2f, targetX, targetY + radius * .8f);
                    }
                    else
                    {
                        var blackPen  = new Pen(Color.FromArgb(255, 0, 0, 0), 3f);
                        var yellowPen = new Pen(Color.FromArgb(255, 255, 255, 0), 2f);
                        g.DrawEllipse(blackPen, targetX - radius * .5f, targetY - radius * .5f, radius, radius);
                        g.DrawEllipse(yellowPen, targetX - radius * .5f, targetY - radius * .5f, radius, radius);
                    }

                    if (!locked)
                    {
                        g.FillRectangle(new SolidBrush(Color.FromArgb(127, 255, 255, 255)), textRectangle);
                    }
                    else
                    {
                        g.FillRectangle(new SolidBrush(Color.FromArgb(170, 255, 255, 0)), textRectangle);
                    }

                    // Setup the text format for drawing the subnotes
                    using (var stringFormat = new StringFormat())
                    {
                        stringFormat.Trimming    = StringTrimming.None;
                        stringFormat.FormatFlags = StringFormatFlags.NoClip | StringFormatFlags.NoWrap;
                        stringFormat.Alignment   = StringAlignment.Near;

                        // Draw the string left aligned
                        g.DrawString(
                            coordinateText,
                            cursorFont,
                            new SolidBrush(Color.Black),
                            textRectangle,
                            stringFormat);
                    }
                }

                // Now copy the bitmap to the cursor
                newCursor = WPFCursorFromBitmap.CreateCursor(cursorBitmap);
            }
            catch
            {
                Trace.WriteLine("Error drawing on cursor");
            }
            finally
            {
                // After the new cursor has been set, the unmanaged resources can be
                // cleaned up that were being used by the old cursor
                if (newCursor != null)
                {
                    uiElement.Cursor = newCursor;
                }
                if (lastCursor != null)
                {
                    lastCursor.Dispose();
                }
                lastCursor = newCursor;

                // Save the new values for cleaning up on the next pass
            }
        }
        private void ExecuteSelectImageCommand()
        {
            testItemController.MinimizeTestItemEditorWindow();

            Window window = new Window();
            window.Height = SystemParameters.VirtualScreenHeight;
            window.Width = SystemParameters.VirtualScreenWidth;
            bool doPicture = false;

            Canvas canvas = new Canvas();
            canvas.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 100,100,100));
            Rectangle rectangle = new Rectangle();
            rectangle.StrokeThickness = 2;
            rectangle.Stroke = Brushes.Red;
            rectangle.Height = 0;
            rectangle.Width = 0;
            Canvas.SetTop(rectangle, 0);
            Canvas.SetLeft(rectangle, 0);
            System.Drawing.Point point = new System.Drawing.Point();

            GlobalHooker hooker = new GlobalHooker();
            MouseHookListener listener = new MouseHookListener(hooker);

            bool isMouseDown = false;
            bool isComplete = false;
            System.Drawing.Point topLeft = new System.Drawing.Point();
            System.Drawing.Point bottomRight = new System.Drawing.Point();

            listener.MouseDown += (o, args) =>
            {
                isMouseDown = true;
                topLeft = System.Windows.Forms.Cursor.Position;
            };

            listener.MouseUp += (o, args) =>
            {

                isMouseDown = false;
                bottomRight = System.Windows.Forms.Cursor.Position;
                isComplete = true;
            };

            listener.Enabled = true;

            Task task = new Task(() =>
            {
                listener.Enabled = true;

                while (!isComplete)
                {
                    Thread.Sleep(250);
                    while (isMouseDown)
                    {
                        point = System.Windows.Forms.Cursor.Position;

                        Rect bounds = new Rect(new Point(topLeft.X, topLeft.Y), new Point(point.X, point.Y));

                        Thread.Sleep(100);
                        Application.Current.Dispatcher.Invoke(new Action(() =>
                        {
                            rectangle.Width = bounds.Width;
                            rectangle.Height = bounds.Height;
                            Canvas.SetTop(rectangle, bounds.Y);
                            Canvas.SetLeft(rectangle, bounds.X);
                        }));
                    }
                }

            });

            canvas.Children.Add(rectangle);
            window.Left = 0;
            window.Top = 0;

            window.Content = canvas;
            window.WindowStyle = new WindowStyle();
            window.ShowInTaskbar = false;
            window.AllowsTransparency = true;

            Bitmap screenshot = new Bitmap(1,1);

            BitmapImage bitmapImage = new BitmapImage();

            window.Topmost = true;

            Task waitTask = new Task(() =>
            {
                Thread.Sleep(3000);
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    using (MemoryStream memory = new MemoryStream())
                    {
                        screenshot = Camera.Capture(0, ScreenCaptureMode.Screen);
                        screenshot.Save(memory, ImageFormat.Png);
                        memory.Position = 0;

                        bitmapImage.BeginInit();
                        bitmapImage.StreamSource = memory;
                        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                        bitmapImage.EndInit();
                    }

                    window.Background = new ImageBrush(bitmapImage);

                    window.Show();
                }));

            });

            task.ContinueWith(t =>
            {
                System.Drawing.Rectangle systemRect = new System.Drawing.Rectangle(topLeft.X, topLeft.Y,
                    bottomRight.X-topLeft.X, bottomRight.Y-topLeft.Y);

                Bitmap tempBitmap = new Bitmap(systemRect.Width, systemRect.Height);

                using (Graphics g = Graphics.FromImage(tempBitmap))
                {
                    g.DrawImage(screenshot, new System.Drawing.Rectangle(0, 0, tempBitmap.Width, tempBitmap.Height),
                        systemRect, GraphicsUnit.Pixel);
                }

                Image = tempBitmap;

                TestItem testItem = testItemController.CurrentTestItem;
                OperationParameter operationParameter = testItem.Operation.GetParameterNamed("Image");
                operationParameter.Value = Image;

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    window.Close();
                    Thread.Sleep(500);
                    testItemController.RestoreTestItemEditorWindow();
                    Thread.Sleep(500);
                    testItemController.RestoreTestItemEditorWindow();
                }));

            });

            waitTask.Start();
            waitTask.ContinueWith(t => task.Start());

            window.Closed += (o, args) =>
            {
                doPicture = false;
                task.Dispose();
            };
        }
Esempio n. 23
0
        /// <summary>
        /// Drawing cell grid lines (navigation lines)
        /// </summary>
        private void DrawCell()
        {
            /*
             * Ниже начинаеться процесс отрисовки линии
             * Данное решение позволяет отрисовать линии (практически) без потери производительности приложения
             * На момент запуска приложение использовано общее 200мб и 430мб после загрузки мира
             */
            const int bitmapSize   = 2000;
            const int bitmapLength = cellSize / bitmapSize;
            const int posCenter    = (bitmapLength / 2);

            System.Drawing.Rectangle size = new System.Drawing.Rectangle(0, 0, bitmapSize, bitmapSize);
            //Выделяем место для наших линий дабы потом их отрендерить в UI
            BitmapSource bsSmallBlack, bsBlackRed, bsBlackGreenHorizontal, bsBlackGreenVertical, bsBlackGreenCenter;

            //Подготавливаем колажи где будут нарисованы наши линии
            using (Bitmap blackBitmap = new Bitmap(bitmapSize, bitmapSize))
                using (Bitmap smallBlackBitmap = new Bitmap(bitmapSize, bitmapSize))
                    using (Bitmap greenBitmapVertical = new Bitmap(bitmapSize, bitmapSize))
                        using (Bitmap greenBitmapHorizontal = new Bitmap(bitmapSize, bitmapSize))
                            using (Bitmap redBitmap = new Bitmap(bitmapSize, bitmapSize))
                            {
                                SolidColorBrush      mediaColorBrushGreen = (SolidColorBrush)App.Current.Resources["OWLOSSuccessAlpha2"];
                                System.Drawing.Color colorGreen           = System.Drawing.Color.FromArgb(mediaColorBrushGreen.Color.A,
                                                                                                          mediaColorBrushGreen.Color.R,
                                                                                                          mediaColorBrushGreen.Color.G,
                                                                                                          mediaColorBrushGreen.Color.B);
                                SolidColorBrush      mediaColorBrushRed = (SolidColorBrush)App.Current.Resources["OWLOSDangerAlpha2"];
                                System.Drawing.Color colorRed           = System.Drawing.Color.FromArgb(mediaColorBrushRed.Color.A,
                                                                                                        mediaColorBrushRed.Color.R,
                                                                                                        mediaColorBrushRed.Color.G,
                                                                                                        mediaColorBrushRed.Color.B);
                                SolidColorBrush      mediaColorBrushBlack = (SolidColorBrush)App.Current.Resources["OWLOSInfoAlpha2"];
                                System.Drawing.Color colorBlack           = System.Drawing.Color.FromArgb(mediaColorBrushBlack.Color.A,
                                                                                                          mediaColorBrushBlack.Color.R,
                                                                                                          mediaColorBrushBlack.Color.G,
                                                                                                          mediaColorBrushBlack.Color.B);
                                System.Drawing.Pen penGreen      = new System.Drawing.Pen(colorGreen, 6);
                                System.Drawing.Pen penRed        = new System.Drawing.Pen(colorRed, 6);
                                System.Drawing.Pen penBlack      = new System.Drawing.Pen(colorBlack, 2);
                                System.Drawing.Pen smallPenBlack = new System.Drawing.Pen(colorBlack, .3f);

                                //Подготавливаем почву для рисования линий
                                using (Graphics gSmallBlack = System.Drawing.Graphics.FromImage(smallBlackBitmap))
                                    using (Graphics gBlack = System.Drawing.Graphics.FromImage(blackBitmap))
                                        using (Graphics gRed = System.Drawing.Graphics.FromImage(redBitmap))
                                        {
                                            //Далее сам процесс отрисовки линий и координат
                                            for (int linePosition = 0; linePosition < cellSize + cellStep; linePosition += cellStep)
                                            {
                                                System.Drawing.Pen      drawingPen = null;
                                                System.Drawing.Graphics graphics   = null;
                                                if (linePosition % 100 == 0)
                                                {
                                                    TextBlock textBlock = new TextBlock
                                                    {
                                                        Text   = linePosition.ToString(),
                                                        Margin = new Thickness(linePosition, 0, 0, 0)
                                                    };

                                                    if (linePosition == cellSize / 2)
                                                    {
                                                        textBlock.Foreground = (SolidColorBrush)App.Current.Resources["OWLOSSuccess"];

                                                        drawingPen = penGreen;
                                                        graphics   = gBlack;
                                                    }
                                                    else
                                                    {
                                                        if (linePosition % 1000 == 0)
                                                        {
                                                            textBlock.Foreground = (SolidColorBrush)App.Current.Resources["OWLOSDanger"];

                                                            if (linePosition < bitmapSize)
                                                            {
                                                                drawingPen = penRed;
                                                                graphics   = gRed;
                                                            }
                                                        }
                                                        else
                                                        {
                                                            textBlock.Foreground = (SolidColorBrush)App.Current.Resources["OWLOSInfo"];
                                                            if (linePosition < bitmapSize)
                                                            {
                                                                drawingPen = penBlack;
                                                                graphics   = gBlack;
                                                            }
                                                        }
                                                    }

                                                    textBlock.VerticalAlignment = VerticalAlignment.Center;
                                                    horisontalNavigationGrid.Children.Add(textBlock);

                                                    textBlock = new TextBlock
                                                    {
                                                        Text   = linePosition.ToString(),
                                                        Margin = new Thickness(0, linePosition, 0, 0)
                                                    };
                                                    if (linePosition == cellSize / 2)
                                                    {
                                                        textBlock.Foreground = (SolidColorBrush)App.Current.Resources["OWLOSSuccess"];
                                                    }
                                                    else
                                                    if (linePosition % 1000 == 0)
                                                    {
                                                        textBlock.Foreground = (SolidColorBrush)App.Current.Resources["OWLOSDanger"];
                                                    }
                                                    else
                                                    {
                                                        textBlock.Foreground = (SolidColorBrush)App.Current.Resources["OWLOSInfo"];
                                                    }

                                                    textBlock.HorizontalAlignment = HorizontalAlignment.Center;
                                                    verticalNavigationGrid.Children.Add(textBlock);
                                                }
                                                else
                                                if (linePosition < bitmapSize)
                                                {
                                                    drawingPen = smallPenBlack;
                                                    graphics   = gSmallBlack;
                                                }

                                                if (drawingPen != null)
                                                {
                                                    System.Drawing.Point verticalBegin = new System.Drawing.Point();
                                                    System.Drawing.Point verticalEnd   = new System.Drawing.Point();

                                                    System.Drawing.Point horizontalBegin = new System.Drawing.Point();
                                                    System.Drawing.Point horizontalEnd   = new System.Drawing.Point();


                                                    if (drawingPen == penGreen)
                                                    {
                                                        //Для зелёных линий отдельно рисуем
                                                        verticalBegin.X   = verticalEnd.X = cellSize / 10;
                                                        verticalEnd.Y     = bitmapSize;
                                                        horizontalBegin.Y = horizontalEnd.Y = cellSize / 10;
                                                        horizontalBegin.X = 0;
                                                        horizontalEnd.X   = bitmapSize;

                                                        using (Graphics gGreenVertical = System.Drawing.Graphics.FromImage(greenBitmapVertical))
                                                        {
                                                            gGreenVertical.DrawLine(drawingPen, verticalBegin, verticalEnd);
                                                        }

                                                        using (Graphics gGreenHorizontal = System.Drawing.Graphics.FromImage(greenBitmapHorizontal))
                                                        {
                                                            gGreenHorizontal.DrawLine(drawingPen, horizontalBegin, horizontalEnd);
                                                        }
                                                    }
                                                    else

                                                    {
                                                        verticalBegin.X   = verticalEnd.X = linePosition;
                                                        verticalEnd.Y     = bitmapSize;
                                                        horizontalBegin.Y = horizontalEnd.Y = linePosition;
                                                        horizontalBegin.X = 0;
                                                        horizontalEnd.X   = bitmapSize;

                                                        graphics.DrawLine(drawingPen, verticalBegin, verticalEnd);
                                                        graphics.DrawLine(drawingPen, horizontalBegin, horizontalEnd);
                                                    }
                                                }
                                            }
                                        }

                                //Переводим из bitmap в bitmapSource
                                System.Drawing.Imaging.BitmapData bitmapData = smallBlackBitmap.LockBits(size, System.Drawing.Imaging.ImageLockMode.ReadOnly, smallBlackBitmap.PixelFormat);
                                bsSmallBlack = BitmapSource.Create(
                                    bitmapData.Width, bitmapData.Height,
                                    smallBlackBitmap.HorizontalResolution, smallBlackBitmap.VerticalResolution,
                                    PixelFormats.Bgra32, null,
                                    bitmapData.Scan0, bitmapData.Stride * bitmapData.Height, bitmapData.Stride);
                                smallBlackBitmap.UnlockBits(bitmapData);

                                //Делаем тоже самое но, предварительно рисуем их друг на друге (комбинируем/накладываем друг на друга)
                                bsBlackRed             = CombineBitmaps(size, blackBitmap, redBitmap);
                                bsBlackGreenHorizontal = CombineBitmaps(size, blackBitmap, redBitmap, greenBitmapHorizontal);
                                bsBlackGreenVertical   = CombineBitmaps(size, blackBitmap, redBitmap, greenBitmapVertical);
                                bsBlackGreenCenter     = CombineBitmaps(size, blackBitmap, redBitmap, greenBitmapHorizontal, greenBitmapVertical);
                            }

            //Рендерим уже из буфера
            for (int posY = 0; posY < bitmapLength; posY++)
            {
                //Поповоду virtualizingstackpanel - https://docs.microsoft.com/en-us/dotnet/api/system.windows.controls.virtualizingstackpanel?view=netframework-4.8 - В самому низу Remarks
                //Поле для больших линий
                VirtualizingStackPanel horizontalVirtualStackPanel = new VirtualizingStackPanel
                {
                    Orientation = Orientation.Horizontal
                };
                ThingLines.Children.Add(horizontalVirtualStackPanel);
                //Поле для маленьких линий
                VirtualizingStackPanel smallHorizontalVirtualStackPanel = new VirtualizingStackPanel
                {
                    Orientation = Orientation.Horizontal
                };
                smallThingLines.Children.Add(smallHorizontalVirtualStackPanel);
                for (int posX = 0; posX < bitmapLength; posX++)
                {
                    BitmapSource bitmapSource;
                    //Рисуем в центре
                    if (posX == posCenter && posY == posCenter)
                    {
                        bitmapSource = bsBlackGreenCenter;
                    }
                    else
                    //Вертикаль
                    if (posX == posCenter)
                    {
                        bitmapSource = bsBlackGreenVertical;
                    }
                    else
                    //Горизонталь
                    if (posY == posCenter)
                    {
                        bitmapSource = bsBlackGreenHorizontal;
                    }
                    //Обычная отрисовка в ряд
                    else
                    {
                        bitmapSource = bsBlackRed;
                    }
                    //Создаем UI Image где будем отображать BitmapSource big и small lines
                    System.Windows.Controls.Image image = new System.Windows.Controls.Image
                    {
                        Source              = bitmapSource,
                        Width               = bitmapSize,
                        Height              = bitmapSize,
                        VerticalAlignment   = VerticalAlignment.Stretch,
                        HorizontalAlignment = HorizontalAlignment.Stretch
                    };
                    horizontalVirtualStackPanel.Children.Add(image);

                    System.Windows.Controls.Image smallImage = new System.Windows.Controls.Image
                    {
                        Source              = bsSmallBlack,
                        Width               = bitmapSize,
                        Height              = bitmapSize,
                        VerticalAlignment   = VerticalAlignment.Stretch,
                        HorizontalAlignment = HorizontalAlignment.Stretch
                    };
                    smallHorizontalVirtualStackPanel.Children.Add(smallImage);
                }
            }

            horisontalNavigationGrid.Visibility = Visibility.Visible;
            verticalNavigationGrid.Visibility   = Visibility.Visible;
        }
        protected override void OnMouseUp(MouseButtonEventArgs e)
        {
            //this method is fired when The zoom in/out tool issues a MouseUp event,
            //so we need to ignore it if we did not initiate the mouse down.
            if (!_myMouseDown)
            {
                base.OnMouseUp(e);
                Trace.TraceInformation("Ignoring MouseUp for zoom in/out");
                return;
            }
            _myMouseDown = false;

            Point mouseUpPoint = e.GetPosition(this);

            //Check to see if the mouseup location is substantially different than the mouse down location, if so then pan and be done
            int dx = Convert.ToInt32(mouseUpPoint.X - _mouseDownPoint.X);
            int dy = Convert.ToInt32(mouseUpPoint.Y - _mouseDownPoint.Y);
            bool moved = (dx < -2 || 2 < dx || dy < -2 || 2 < dy);

            if (moved)
            {
                Trace.TraceInformation("Mouse up passed to pan");
                mapControl.Map.Pan(dx, dy);
                e.Handled = true;
                return;
            }

            //Check to see if there is an observation related to this location.  If so - edit it, then be done
            var drawingPoint = new System.Drawing.Point(Convert.ToInt32(mouseUpPoint.X), Convert.ToInt32(mouseUpPoint.Y));
            Observation observation = GetObservation(drawingPoint);
            if (observation != null)
            {
                //Trace.TraceInformation("Mouse up found observation");

                var dlg = new SelectionDialog(observation);
                dlg.ShowDialog();

                if (dlg.Action == SelectionAction.Delete)
                {
                    //Trace.TraceInformation("Delete");
                    observation.Delete();
                    e.Handled = true;
                }
                if (dlg.Action == SelectionAction.Edit)
                {
                    //Trace.TraceInformation("Edit");
                    Task.AddObservationAsActive(observation);
                    MobileApplication.Current.Transition(new EditObservationAttributesPage());
                    e.Handled = true;
                }
                return;
            }
            //Trace.TraceInformation("Mouse up passed to base");
            base.OnMouseUp(e);
        }
        /// <summary>
        /// Changes the cursor for this control to show the coordinates
        /// </summary>
        /// <param name="uiElement"></param>
        private void SetCoordinatesOnCursor(FrameworkElement uiElement)
        {
            Point coordinate = locked ? lockPoint : lastCoordinate;
            Cursor newCursor = null;
            var cursorFont = new Font("Arial", 8f);

            try
            {
                // Lets get the string to be printed
                string coordinateText = coordinate.X.ToString(xFormat) + "," + coordinate.Y.ToString(yFormat);
                // Calculate the rectangle required to draw the string
                SizeF textSize = GetTextSize(coordinateText, cursorFont);

                // ok, so here's the minimum 1/4 size of the bitmap we need, as the
                // Hotspot for the cursor will be in the centre of the bitmap.
                int minWidth = 8 + (int) Math.Ceiling(textSize.Width);
                int minHeight = 8 + (int) Math.Ceiling(textSize.Height);

                // If the bitmap needs to be resized, then resize it, else just clear it
                if (cursorBitmap.Width < minWidth*2 || cursorBitmap.Height < minHeight*2)
                {
                    Bitmap oldBitmap = cursorBitmap;
                    cursorBitmap = new Bitmap(Math.Max(cursorBitmap.Width, minWidth*2),
                                              Math.Max(cursorBitmap.Height, minHeight*2));
                    oldBitmap.Dispose();
                }

                // Get the centre of the bitmap which will be the Hotspot
                var centre = new System.Drawing.Point(cursorBitmap.Width/2, cursorBitmap.Height/2);
                /// Calculate the text rectangle
                var textRectangle = new Rectangle(centre.X + 8, centre.Y + 8, minWidth - 8, minHeight - 8);

                int diff = (int) cursorPosition.X + textRectangle.Right/2 - 3 - (int) uiElement.ActualWidth;

                if (diff > 0)
                {
                    textRectangle.Location = new System.Drawing.Point(textRectangle.Left - diff, textRectangle.Top);
                }

                // Draw the target symbol, and the coordinate text on the bitmap
                using (Graphics g = Graphics.FromImage(cursorBitmap))
                {
                    g.SmoothingMode = SmoothingMode.AntiAlias;
                    // This line causes a crash on laptops when you render a string
                    // g.CompositingMode = CompositingMode.SourceCopy;
                    g.Clear(Color.Transparent);

                    float targetX = centre.X;
                    float targetY = centre.Y;

                    float radius = 30;

                    if (!locked)
                    {
                        var blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 1.4f);
                        g.DrawEllipse(blackPen, targetX - radius*.5f, targetY - radius*.5f, radius, radius);
                        g.DrawLine(blackPen, targetX - radius*.8f, targetY, targetX - 2f, targetY);
                        g.DrawLine(blackPen, targetX + 2f, targetY, targetX + radius*.8f, targetY);
                        g.DrawLine(blackPen, targetX, targetY - radius*.8f, targetX, targetY - 2f);
                        g.DrawLine(blackPen, targetX, targetY + 2f, targetX, targetY + radius*.8f);
                    }
                    else
                    {
                        var blackPen = new Pen(Color.FromArgb(255, 0, 0, 0), 3f);
                        var yellowPen = new Pen(Color.FromArgb(255, 255, 255, 0), 2f);
                        g.DrawEllipse(blackPen, targetX - radius*.5f, targetY - radius*.5f, radius, radius);
                        g.DrawEllipse(yellowPen, targetX - radius*.5f, targetY - radius*.5f, radius, radius);
                    }

                    if (!locked)
                        g.FillRectangle(new SolidBrush(Color.FromArgb(127, 255, 255, 255)), textRectangle);
                    else
                        g.FillRectangle(new SolidBrush(Color.FromArgb(170, 255, 255, 0)), textRectangle);

                    // Setup the text format for drawing the subnotes
                    using (var stringFormat = new StringFormat())
                    {
                        stringFormat.Trimming = StringTrimming.None;
                        stringFormat.FormatFlags = StringFormatFlags.NoClip | StringFormatFlags.NoWrap;
                        stringFormat.Alignment = StringAlignment.Near;

                        // Draw the string left aligned
                        g.DrawString(
                            coordinateText,
                            cursorFont,
                            new SolidBrush(Color.Black),
                            textRectangle,
                            stringFormat);
                    }
                }

                // Now copy the bitmap to the cursor
                newCursor = WPFCursorFromBitmap.CreateCursor(cursorBitmap);
            }
            catch
            {
                Trace.WriteLine("Error drawing on cursor");
            }
            finally
            {
                // After the new cursor has been set, the unmanaged resources can be
                // cleaned up that were being used by the old cursor
                if (newCursor != null)
                {
                    uiElement.Cursor = newCursor;
                }
                if (lastCursor != null)
                {
                    lastCursor.Dispose();
                }
                lastCursor = newCursor;

                // Save the new values for cleaning up on the next pass
            }
        }
Esempio n. 26
0
        public DPoint CrawlToTip(Frame target, System.Drawing.Point start, System.Drawing.Point origin, int threshold = 50, int maxDistance = 30, int maxHopDistance = 2, bool crawlingAway = true)
        {
            var loopCount  = 0;
            var startColor = target.GetColor(start);

            if (startColor.GetBrightness() == 0)
            {
                return(start);
            }

            var bestDistance        = start.Distance(origin);
            var bestPoint           = start;
            var visited             = FrameFilterExtensions.CreateJaggedArray <bool[][]>(maxDistance * 2 + 1, maxDistance * 2 + 1);
            var visitedOffsetX      = start.X - maxDistance;
            var visitedOffsetY      = start.Y - maxDistance;
            var bestLocationLockpad = new object();

            var queue = new Queue <System.Drawing.Point>();

            queue.Enqueue(start);


            while (queue.Count > 0 && loopCount < 500)
            {
                loopCount++;
                var point      = queue.Dequeue();
                var candidates = getCandidateLocations(point, maxHopDistance);

                Parallel.ForEach(candidates, p =>
                {
                    //Check bounds
                    if (p.X < 0 || p.X >= target.Width ||
                        p.Y < 0 || p.Y >= target.Height)
                    {
                        return;
                    }

                    //Check if within search radius
                    var distFromStart = p.Distance(start);

                    if (distFromStart > maxDistance)
                    {
                        return;
                    }

                    //Check if already checked
                    var visitedX = p.X - visitedOffsetX;
                    var visitedY = p.Y - visitedOffsetY;
                    var exists   = visited[visitedX][visitedY];

                    if (exists)
                    {
                        return;
                    }

                    //Mark as checked, regardless of outcome
                    lock (visited)
                    {
                        visited[visitedX][visitedY] = true;
                    }

                    //Check if within color range
                    var distFromStartColor = target.GetColor(p).Distance(startColor);

                    if (distFromStartColor > threshold)
                    {
                        return;
                    }

                    //See if distance is further
                    var dist = p.Distance(origin);

                    //Don't bother if distance is much worse than the best (maximizing distance)
                    if (crawlingAway && dist < bestDistance * 0.975)
                    {
                        return;
                    }

                    //Or opposite if crawling closer (minimizing distance)
                    else if (!crawlingAway && dist > bestDistance * 1.025)
                    {
                        return;
                    }

                    //Save best distance (away = maximizing, towards = minimizing)
                    if ((crawlingAway && dist > bestDistance) || (!crawlingAway && dist < bestDistance))
                    {
                        lock (bestLocationLockpad)
                        {
                            bestDistance = dist;
                            bestPoint    = p;
                        }
                    }

                    lock (queue)
                    {
                        queue.Enqueue(p);
                    }
                });
            }

            return(bestPoint);
        }
        /// <summary>
        /// Call back function for take snapshot command dependency property,
        /// when no video device source selected show appropriate message
        /// or message currently display in user-control based on user input.
        /// </summary>
        /// <exception cref="InvalidOperationException">Wraps and throws <see cref="InvalidOperationException"/> when any exception is thrown from this method.</exception>
        public void TakeSnapshotCallback()
        {
            try
            {
                var playerPoint = new Drawing.Point();

                //// Get the position of the source video device player.
                if (string.IsNullOrWhiteSpace(this.VideoSourceId))
                {
                    var noVideoDeviceSourcePoint = this.NoVideoSourceGrid.PointToScreen(new Point(0, 0));
                    playerPoint.X = (int)noVideoDeviceSourcePoint.X;
                    playerPoint.Y = (int)noVideoDeviceSourcePoint.Y;
                }
                else
                {
                    playerPoint = this.VideoSourcePlayer.PointToScreen(new Drawing.Point(this.VideoSourcePlayer.ClientRectangle.X, this.VideoSourcePlayer.ClientRectangle.Y));
                }

                if (double.IsNaN(this.VideoPreviewWidth) || double.IsNaN(this.VideoPreviewHeight))
                {
                    using (var bitmap = new Bitmap((int)this.VideoSourceWindowsFormsHost.ActualWidth, (int)this.VideoSourceWindowsFormsHost.ActualHeight))
                    {
                        using (var graphicsFromImage = Graphics.FromImage(bitmap))
                        {
                            graphicsFromImage.CopyFromScreen(playerPoint, Drawing.Point.Empty, new Drawing.Size((int)this.VideoSourceWindowsFormsHost.ActualWidth, (int)this.VideoSourceWindowsFormsHost.ActualHeight));
                        }

                        this.SnapshotBitmap = new Bitmap(bitmap);
                    }
                }
                else
                {
                    using (var bitmap = new Bitmap((int)this.VideoPreviewWidth, (int)this.VideoPreviewHeight))
                    {
                        using (var graphicsFromImage = Graphics.FromImage(bitmap))
                        {
                            graphicsFromImage.CopyFromScreen(playerPoint, Drawing.Point.Empty, new Drawing.Size((int)this.VideoPreviewWidth, (int)this.VideoPreviewHeight));
                        }

                        this.SnapshotBitmap = new Bitmap(bitmap);
                    }
                }
            }
            catch (Exception exception)
            {
                throw new InvalidOperationException("Er is een fout ontstaan tijdens het maken van een afbeelding van het geselecteerde video-apparaat", exception);
            }
        }
Esempio n. 28
0
 public static extern IntPtr WindowFromPoint(System.Drawing.Point pt);
Esempio n. 29
0
 public static Point ToWpf(this System.Drawing.Point p)
 {
     return(new Point(p.X, p.Y));
 }
    private void tcpipServer_OnCalibrationFeedbackPoint(long time, int packagenumber, int targetX, int targetY,
                                                        int gazeX, int gazeY, float distance, int acquisitionTime)
    {
      CalibrationWindow.Instance.Dispatcher.Invoke
          (
              DispatcherPriority.ApplicationIdle,
              new Action
                  (
                  delegate
                  {
                    //pass info from the dedicated interface to the tracker class
                    var target = new System.Drawing.Point(targetX, targetY);
                    var gaze = new GTPoint(gazeX, gazeY);
                    //tracker.SaveRecalibInfo(time, packagenumber, target, gaze);

                    /* outputting the data in a local class */
                    string del = " ";
                    string msg = DateTime.Now.Ticks + del
                                 + time + del
                                 + packagenumber + del
                                 + targetX + del
                                 + targetX + del
                                 + gazeX + del
                                 + gazeY + del
                                 + distance + del
                                 + acquisitionTime;
                    Output.Instance.appendToFile(msg);
                  }
                  )
          );
    }
Esempio n. 31
0
 public POINT(System.Drawing.Point pt) : this(pt.X, pt.Y)
 {
 }
Esempio n. 32
0
 public static extern bool ScreenToClient(IntPtr handle, ref System.Drawing.Point screen);
Esempio n. 33
0
        public string Preprocess_Final(string filepath, string outPath, bool displayMode, int thresholding)
        {
            StringBuilder sb = new StringBuilder();

            displayMode = false;
            WriteToLog("Loading Image : " + filepath);
            Bitmap load;

            try
            {
                load = new Bitmap(filepath);
            }
            catch (Exception ex)
            {
                return("FAIL!");
            }


            var start = DateTime.Now;

            WriteToLog("Running Background Detection ...");
            Bgr backgroundColor = Heuristics.DetectBackground(load, 20);

            WriteToLog("Detected Background : " + backgroundColor.ToString());
            WriteToLog("Detected Background Completed in " + (DateTime.Now - start).TotalSeconds.ToString() +
                       " seconds");


            var backgroundGuess = new Image <Bgr, Byte>(100, 100, backgroundColor);


            WriteToLog("Running Shred Extraction ");
            WriteToLog("Image Size : " + load.Height * load.Width + " Pixels");

            string imagesrc = filepath;
            Bitmap source   = new Bitmap(imagesrc);

            WriteToLog("beginning flood fill...");
            System.Drawing.Point startPoint = Heuristics.GetStartingFloodFillPoint(source,
                                                                                   System.Drawing.Color.FromArgb(255, (int)backgroundColor.Red,
                                                                                                                 (int)backgroundColor.Green,
                                                                                                                 (int)backgroundColor.Blue));
            Bitmap Mask = Preprocessing.FloodFill(source, startPoint.X, startPoint.Y, 50, backgroundColor);

            WriteToLog("flood fill complete...");
            WriteToLog("extracting objects...");
            List <Bitmap> extractedobj = Preprocessing.ExtractImages(source, Mask);

            WriteToLog("Extracted " + extractedobj.Count + " objects");


            // Prompt for input directory and Write to file

            Console.Write("Enter Output Directory (Default is Working): ");
            string directory = outPath;// Console.ReadLine();

            if (String.IsNullOrEmpty(directory) || !Directory.Exists(directory))
            {
                WriteToLog("Writing to Working Directory");
                directory = string.Empty;
            }
            else
            {
                directory += "\\";
            }

            WriteToLog("Rotating Images");
            int ii     = 0;
            int maxLen = extractedobj.Count.ToString().Length;

            foreach (Bitmap bm in extractedobj)
            {
                Bitmap bm2 = Preprocessing.Orient(bm);
                bm2.Save(directory + "image" + ii.ToString("D" + maxLen) + ".png");
                ii++;
            }
            WriteToLog("Wrote Files To Disk");
            return(sb.ToString());
        }
Esempio n. 34
0
		public System.Drawing.PointF TileToWorldPos(double tile_x, double tile_y, int zoom)
			{
			System.Drawing.PointF p = new System.Drawing.Point();
			double n = Math.PI - ((2.0 * Math.PI * tile_y) / Math.Pow(2.0, zoom));

			p.X = (float)((tile_x / Math.Pow(2.0, zoom) * 360.0) - 180.0);
			p.Y = (float)(180.0 / Math.PI * Math.Atan(Math.Sinh(n)));

			return p;
			}