public void Setup()
        {
            m_StartSegment = Substitute.For <ITurnCircleArcSegment>();
            m_MiddleSegment = Substitute.For <ITurnCircleArcSegment>();
            m_EndSegment = Substitute.For <ITurnCircleArcSegment>();

            m_Path = Substitute.For <IPath>();
            var segments = new List <IPolylineSegment>
                           {
                               m_StartSegment,
                               m_MiddleSegment,
                               m_EndSegment
                           };

            m_Path.Segments.Returns(segments);

            m_ArcSegmentOne = new ArcSegment(new Point(10.0,
                                                       10.0),
                                             new Size(10.0,
                                                      10.0),
                                             45.0,
                                             false,
                                             SweepDirection.Clockwise,
                                             false);

            m_LineSegment = new LineSegment(new Point(20.0,
                                                      20.0),
                                            false);

            m_ArcSegmentTwo = new ArcSegment(new Point(30.0,
                                                       30.0),
                                             new Size(30.0,
                                                      30.0),
                                             90.0,
                                             false,
                                             SweepDirection.Counterclockwise,
                                             false);

            m_ArcSegmentThree = new ArcSegment(new Point(40.0,
                                                         40.0),
                                               new Size(40.0,
                                                        40.0),
                                               135.0,
                                               false,
                                               SweepDirection.Counterclockwise,
                                               false);


            m_Point = new Point(10.0,
                                10.0);

            m_Helper = Substitute.For <IPathSegmentHelper>();
            m_Helper.SegmentToLineSegment(Line.Unknown).ReturnsForAnyArgs(m_LineSegment);
            m_Helper.SegmentToArcSegment(TurnCircleArcSegment.Unknown).ReturnsForAnyArgs(m_ArcSegmentOne,
                                                                                         m_ArcSegmentTwo,
                                                                                         m_ArcSegmentThree);
            m_Helper.PointRelativeToOrigin(null).ReturnsForAnyArgs(m_Point);

            m_Converter = new RacetrackPathUTurnToFiguresConverter(m_Helper);
        }
Example #2
1
 /// <summary>
 /// Returns a value indicating whether a point is inside the bounding box of the element.
 /// </summary>
 /// <param name="element"></param>
 /// <param name="pointRelativeToElement"></param>
 /// <returns></returns>
 public static bool ContainsPoint(this FrameworkElement element, Point pointRelativeToElement)
 {
     //TODO: Silverlight allows more complex geometries than Rectangle.
     Rect rect = new Rect { X = 0, Y = 0, Width = element.ActualWidth, Height=element.ActualHeight };
     
     return rect.Contains(pointRelativeToElement);            
 }
Example #3
0
 /// <summary>
 /// Convert from WPF point to core point.
 /// </summary>
 public static Point[] Convert(RPoint[] points)
 {
     Point[] myPoints = new Point[points.Length];
     for (int i = 0; i < points.Length; i++)
         myPoints[i] = Convert(points[i]);
     return myPoints;
 }
Example #4
0
        protected override Size ArrangeOverride(Size finalSize)
        {
            if (GetValues(this) != null)
            {
                double total = 0.0;
                for (int i = 0; i < InternalChildren.Count; i++)
                {
                    total += (double)(GetValues(this)[i]);
                }
                double offsetAngle = 0.0;

                double radius = finalSize.Width < finalSize.Height ? finalSize.Width / 2 : finalSize.Height / 2;
                //radius -= 2;
                Point beginFigure = new Point(finalSize.Width / 2, finalSize.Height / 2);
                Point lineToBeforeTransform = new Point(beginFigure.X + radius, beginFigure.Y);
                for (int i = 0; i < InternalChildren.Count; i++)
                {
                    ContentControl container = InternalChildren[i] as ContentControl;
                    double wedgeAngle = (double)(GetValues(this)[i]) * 360 / total;
                    RotateTransform rt = new RotateTransform(offsetAngle, beginFigure.X, beginFigure.Y);
                    container.SetValue(PiePanel.BeginFigurePointProperty, beginFigure);
                    container.SetValue(PiePanel.LineToPointProperty, rt.Transform(lineToBeforeTransform));
                    container.SetValue(PiePanel.WedgeAngleProperty, wedgeAngle);
                    offsetAngle += wedgeAngle;
                    Rect r = new Rect(finalSize);
                    container.Arrange(r);
                }
            }
            return finalSize;
        }
        public void It_sets_the_new_position_to_24_24_when_the_initial_position_is_10_10_and_the_speed_is_20_and_the_direction_is_45_degrees_and_the_timeElapsed_is_1000()
        {
            var result = Calculator.CalculateNewPosition(new Point(10, 10), 45D.ToRadians(), 20, 1000);

            var expectedResult = new Point(24, -4);
            Assert.IsTrue(expectedResult.IsEqualTo(result), string.Format("{0} is not equal to {1}", expectedResult, result));
        }
        public InfoLinkDecal()
        {
            MetaData = new InfoLinkMetaData() { Source = "http://" };
            Stretch = System.Windows.Media.Stretch.Uniform;
            Size = 1;
            CanResize = false;
            Stretch = System.Windows.Media.Stretch.None;
            Center = new System.Windows.Point(1, 1);
            PinPoint = new System.Windows.Point(1, 1);
            CanMove = false;

            OpenUrl = new DelegateCommand(() =>
            {
                if (!MetaData.Source.StartsWith("http://"))
                {
                    MetaData.Source = "http://" + MetaData.Source;
                }
            #if WINDOWS_PHONE
                Microsoft.Phone.Controls.PhoneApplicationFrame frame = Application.Current.RootVisual as Microsoft.Phone.Controls.PhoneApplicationFrame;
                frame.Navigate(new Uri(MetaData.Source));
            #elif SILVERLIGHT

                HtmlPage.Window.Navigate(new Uri(MetaData.Source), "_blank");
            #else
                Process.Start(MetaData.Source);
            #endif
            }, CanOpenUrl);
        }
 public ShapeDrawingCanvas() 
 {
     coordinateOrigin = new System.Windows.Point(50, 400);
     this.MouseLeftButtonDown += new MouseButtonEventHandler(ShapeDrawingCanvas_MouseLeftButtonDown);
     this.MouseMove += new MouseEventHandler(ShapeDrawingCanvas_MouseMove);
     this.MouseLeftButtonUp += new MouseButtonEventHandler(ShapeDrawingCanvas_MouseLeftButtonUp);
 }
Example #8
0
        public static WPFMEDIA.LineGeometry PerpendicularLine(WPF.Point StartPoint, WPF.Point EndPoint, double Length)
        {
            //Get Current Angle Don't need the actual angle, radians is fine.
            double angle = CurrentAngle(StartPoint, EndPoint);
            double radians = Math.Atan2(StartPoint.Y - EndPoint.Y, StartPoint.X - EndPoint.X);

            //Take 90 deg
            double newAngle = angle + 90;
            double newRadians = radians + Math.PI / 2;

            //need to determine the shift.

            double shiftX = Length * Math.Cos(newRadians);
            //double shiftX2 = Length * Math.Cos(newAngle * Math.PI / 180);

            double shiftY = Length * Math.Sin(newRadians);

            double newStartPointX = StartPoint.X - shiftX;
            double newStartPointY = StartPoint.Y - shiftY;

            double newEndPointX = StartPoint.X + shiftX;
            double newEndPointY = StartPoint.Y + shiftY;

            WPF.Point newStartPoint = new WPF.Point(newStartPointX, newStartPointY);
            WPF.Point newEndPoint = new WPF.Point(newEndPointX, newEndPointY);

            //get the second point

            //draw line from center of the point.
            WPFMEDIA.LineGeometry newLine = new System.Windows.Media.LineGeometry(newStartPoint, newEndPoint);
            return newLine;
        }
        public WindowTimer(Table table)
        {
            Table = table;
            InitializeComponent();

            // drag by right mouse click
            System.Windows.Point startPosition = new System.Windows.Point();
            PreviewMouseRightButtonDown += (sender, e) =>
            {
                startPosition = e.GetPosition(this);
            };
            PreviewMouseMove += (sender, e) =>
            {
                if (!Config.HudTimerLocationLocked && e.RightButton == MouseButtonState.Pressed)
                {
                    System.Windows.Point endPosition = e.GetPosition(this);
                    Vector vector = endPosition - startPosition;
                    Left += vector.X;
                    Top += vector.Y;

                    Rectangle cr = WinApi.GetClientRectangle(Table.Handle);
                    double x = (Left - cr.Left) / cr.Width;
                    double y = (Top - cr.Top) / cr.Height;
                    Config.HudTimerLocationsX[(int)Table.TableHud.TableSize] = (float)x;
                    Config.HudTimerLocationsY[(int)Table.TableHud.TableSize] = (float)y;
                }
            };
        }
        public void Beweeg()
        {
            if (Locatie.X > 1000 || Locatie.Y > 1000)
            {
                _gestopt = true;
                return;
            }
            if (Locatie.X < -1000 || Locatie.Y < -1000)
            {
                _gestopt = true;
                return;
            }

            if (Spel.Is_er_een_hindernis_in_de_weg(NieuweLocatie(), Formaat))
            {
                _gestopt = true;
                return;
            }

            var ventje_geraakt = Spel.Is_hier_het_ventje(NieuweLocatie(), Formaat);
            if (ventje_geraakt)
            {
                _gestopt = true;
                Spel.Ventje_is_geraakt();
            }
            else
            {
                Locatie = NieuweLocatie();
            }
        }
Example #11
0
        /// <summary>
        /// Updates the canvas information (for if canvas size changes)
        /// </summary>
        public void Update(Size canvasSize, int gridSize)
        {
            var previousSize = CanvasSize;

            Center = new Point(canvasSize.Width / 2, canvasSize.Height / 2);

            RotationTransform = new RotateTransform(45, Center.X, Center.Y);
            FlipTransform = new ScaleTransform(1, -1, Center.X, Center.Y);
            Transforms = new TransformGroup();
            Transforms.Children.Add(RotationTransform);
            Transforms.Children.Add(FlipTransform);

            RotationTransformReverse = new RotateTransform(-45, Center.X, Center.Y);
            TransformsReverse = new TransformGroup();
            TransformsReverse.Children.Add(FlipTransform);
            TransformsReverse.Children.Add(RotationTransform);

            CanvasSize = canvasSize;
            Grid = new Size((int)(canvasSize.Width / gridSize), (int)(canvasSize.Height / gridSize));
            GridSquareSize = new Size(gridSize, gridSize);
            LastCanvas = this;

            ClipRegion = new RectangleGeometry(new Rect(new Point(20, 20), new Size(canvasSize.Width - 40, canvasSize.Height - 40)));

            if (OnCanvasSizeChanged != null && !previousSize.Equals(CanvasSize))
                OnCanvasSizeChanged(previousSize, CanvasSize);
        }
		/// <summary>
		/// Arranges the adorner element on the specified adorner panel.
		/// </summary>
		public override void Arrange(AdornerPanel panel, UIElement adorner, Size adornedElementSize)
		{
			Point p = new Point(0, 0);
			if (shape is Line)
			{
				var s = shape as Line;
				double x, y;
				
				if (alignment == PlacementAlignment.BottomRight)
				{
					x = s.X2;
					y = s.Y2;
				}
				else
				{
					x = s.X1;
					y = s.Y1;
				}
				p = new Point(x, y);
			} else if (shape is Polygon) {
				var pg = shape as Polygon;
				p = pg.Points[Index];
			} else if (shape is Polyline) {
				var pg = shape as Polyline;
				p = pg.Points[Index];
			}

			var transform = shape.RenderedGeometry.Transform;
			p = transform.Transform(p);
			
			adorner.Arrange(new Rect(p.X - 3.5, p.Y - 3.5, 7, 7));
		}
Example #13
0
 private void SetVolumeFromPosition(Point position)
 {
     var volume = position.X / VolumeMax.Width;
     if (volume < 0) volume = 0;
     if (volume > 10) volume = 10;
     SetVolume(volume);
 }
Example #14
0
        public void Arc(object backend, double xc, double yc, double radius, double angle1, double angle2, bool inverse)
        {
            var c = (DrawingContext)backend;

            if (angle1 == angle2)
                return;

            if (angle1 > angle2)
                angle2 += (Math.Truncate (angle1 / 360) + 1) * 360;

            double nextAngle;

            do {
                nextAngle = angle2 - angle1 < 360 ? angle2 : angle1 + 359;

                var p1 = new SW.Point (xc + radius * Math.Cos (angle1 * Math.PI / 180.0), yc + radius * Math.Sin (angle1 * Math.PI / 180.0));
                var p2 = new SW.Point (xc + radius * Math.Cos (nextAngle * Math.PI / 180.0), yc + radius * Math.Sin (nextAngle * Math.PI / 180.0));

                c.ConnectToLastFigure (p1, true);

                var largeArc = inverse ? nextAngle - angle1 < 180 : nextAngle - angle1 > 180;
                var direction = inverse ? SweepDirection.Counterclockwise : SweepDirection.Clockwise;
                c.Path.Segments.Add (new ArcSegment (p2, new SW.Size (radius, radius), 0, largeArc, direction, true));
                angle1 = nextAngle;
                c.EndPoint = p2;
            }
            while (nextAngle < angle2);
        }
Example #15
0
        /// <summary>
        /// Moves the image around following your finger.
        /// </summary>
        private void OnDragDelta(object sender, DragDeltaGestureEventArgs e)
        {
            var translationDelta = new Point(e.HorizontalChange, e.VerticalChange);

            if (IsDragValid(1, translationDelta))
                UpdateImagePosition(translationDelta);
        }
Example #16
0
		public void Equals ()
		{
			Point p = new Point (4, 5);
			Assert.IsTrue (p.Equals (new Point (4, 5)));
			Assert.IsFalse (p.Equals (new Point (5, 4)));
			Assert.IsFalse (p.Equals (new object()));
		}
 public override void MouseMove(Point position)
 {
     if (IsWorking)
     {
         SetEndPoint(position);
     }
 }
 public ProjectielVanMonsterkeNaarLinks(ISpel spel, Point startpunt, Brush brush)
     : base(brush)
 {
     Spel = spel;
     Locatie = startpunt;
     _gestopt = false;
 }
Example #19
0
        private void ZoomingChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (Handler != null)
            {
                var oldlocation = new Point(Handler.ActualWidth / 2 / Handler.Zoom, Handler.ActualHeight / 2 / Handler.Zoom);
                var newLocation = oldlocation;

                if (!e.NewValue.Equals(e.OldValue))
                {
                    if (e.NewValue > e.OldValue)
                    {
                        for (var i = e.NewValue; i > e.OldValue; i--)
                        {
                            Handler.ZoomIn();
                            newLocation.Y = newLocation.Y * 0.9;
                            newLocation.X = newLocation.X * 0.9;
                        }
                    }
                    else if (e.NewValue < e.OldValue)
                    {
                        for (var i = e.NewValue; i < e.OldValue; i++)
                        {
                            Handler.ZoomOut();
                            newLocation.Y = newLocation.Y / 0.9;
                            newLocation.X = newLocation.X / 0.9;
                        }
                    }
                    var y = newLocation.Y - oldlocation.Y;
                    var x = newLocation.X - oldlocation.X;

                    Handler.MoveMap(x, y);
                }
                
            }        
        }
Example #20
0
 /// <summary>
 /// Convert Point from real world coordinate to screen coordinate
 /// Real World => Device (Foosbot World) => Frame Dimensions => Screen Dimensions
 /// </summary>
 /// <param name="realWorldPoint">Point in coordinates of Real World</param>
 /// <returns>Point in coordinates of Screen</returns>
 protected Point ConvertPointFromRealWorldToScreen(Point realWorldPoint)
 {
     Point devicePoint = Data.TableToDeviceCoordinates(realWorldPoint);
     Point framePoint = TransformAgent.Data.InvertTransform(devicePoint);
     Point screenPoint = _screen.FrameToScreenCoordinates(framePoint);
     return screenPoint;
 }
    protected override void OnRender(DrawingContext drawingContext) {
      base.OnRender(drawingContext);
      if (packing == null) return;
      // the container should fill the whole size
      var scalingX = renderSize.Width / Packing.BinShape.Width;
      var scalingY = renderSize.Height / Packing.BinShape.Width;
      // draw container
      drawingContext.DrawRectangle(Brushes.LightGray, new Pen(Brushes.Black, 1), new Rect(new Point(0, 0), renderSize));

      var selectedBrush = Brushes.MediumSeaGreen;
      var unselectedBrush = selectedItemKey < 0 ? selectedBrush : Brushes.DarkGray;

      foreach (var t in Packing.Items) {
        var key = t.Key;
        var item = t.Value;
        var pos = Packing.Positions[key];

        var scaledPos = new Point(pos.X * scalingX, pos.Y * scalingY);

        var scaledSize = pos.Rotated ?
          new Size(item.Height * scalingX, item.Width * scalingY) :
          new Size(item.Width * scalingX, item.Height * scalingY);

        var brush = key == selectedItemKey ? selectedBrush : unselectedBrush;
        drawingContext.DrawRectangle(brush, new Pen(Brushes.Black, 1), new Rect(scaledPos, scaledSize));
      }
    }
 private void ImageMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
 {
     var img = (Image)sender;
     img.CaptureMouse();
     _startImgMove = e.GetPosition(viewImg);
     _originImgMove = new Point(viewImg.HorizontalOffset, viewImg.VerticalOffset);
 }
Example #23
0
		public EllipseGeometry (Point center, double radiusX, double radiusY, Transform transform)
		{
			Transform = transform;
			Center = center;
			RadiusX = radiusX;
			RadiusY = radiusY;
		}
 public static CustomPopupPlacement[] CustomPopupPlacementCallbackImpl(Size popupSize, Size targetSize, Point offset)
 {
     return new []
     {
         new CustomPopupPlacement(new Point(targetSize.Width/2 - popupSize.Width/2, targetSize.Height + 14), PopupPrimaryAxis.Horizontal) 
     };
 }
Example #25
0
 private static CustomPopupPlacement[] OnPlacementCallback(Size popupSize, Size targetSize, Point offset) {
     return new[] {
         new CustomPopupPlacement {
             Point = new Point(0, targetSize.Height)
         }
     };
 }
        protected override Size ArrangeOverride(Size finalSize)
        {
            Size inflate = new Size();

            if (finalSize.Width < totChildWidth)
                inflate.Width = (totChildWidth - finalSize.Width) / InternalChildren.Count;

            Point offset = new Point();
            if (finalSize.Width > totChildWidth)
                offset.X = -(finalSize.Width - totChildWidth)/2;

            double totalFinalWidth = 0.0;
            foreach (UIElement child in InternalChildren)
            {
                Size childFinalSize = child.DesiredSize;
                childFinalSize.Width -= inflate.Width;
                childFinalSize.Height = finalSize.Height;

                child.Arrange(new Rect(offset, childFinalSize));

                offset.Offset(childFinalSize.Width, 0);
                totalFinalWidth += childFinalSize.Width;
            }

            return new Size(totalFinalWidth, finalSize.Height);
        }
 public ImageJigsawRectPiece(BitmapImage imageSource, int col, int row, double pieceSize)
     : base(imageSource, col, row, pieceSize)
 {
     this._origin = new Point((col * pieceSize), (double)(row * pieceSize));
     this.Position = new Point((col * pieceSize), (double)(row * pieceSize));
     base.InitShapeProperties();
 }
        public void It_sets_the_new_position_to_minus_10_10_when_the_initial_position_is_10_10_and_the_speed_is_20_and_the_direction_is_270_degrees_and_the_timeElapsed_is_1000()
        {
            var result = Calculator.CalculateNewPosition(new Point(10, 10), 270D.ToRadians(), 20, 1000);

            var expectedResult = new Point(-10, 9); //should be (-10,10) but here's a minor rounding issue ...
            Assert.IsTrue(expectedResult.IsEqualTo(result), string.Format("{0} is not equal to {1}", expectedResult, result));
        }
Example #29
0
        private void CalculateStartAndEndPoint(out Point startPoint, out Point endPoint)
        {
            startPoint = new Point();
            endPoint = new Point();

            double width = this.AdornedElement.RenderSize.Width;
            double height = this.AdornedElement.RenderSize.Height;

            if (this.isSeparatorHorizontal)
            {
                endPoint.X = width;
                if (!this.IsInFirstHalf)
                {
                    startPoint.Y = height;
                    endPoint.Y = height;
                }
            }
            else
            {
                endPoint.Y = height;
                if (!this.IsInFirstHalf)
                {
                    startPoint.X = width;
                    endPoint.X = width;
                }
            }
        }
Example #30
0
 /// <summary>
 /// Initializes a new character instance.
 /// </summary>
 /// <param name="p0">Lower left character position.</param>
 /// <param name="size">Size of the character.</param>
 /// <param name="uiTaskSchedule">Scheduler associated with the UI thread.</param>
 public Character(Point p0, Vector size, TaskScheduler uiTaskSchedule)
     : base(uiTaskSchedule)
 {
     this.Position = new Quadrilateral(p0, size);
     this.Gravity = CharacterGravityState.Down;
     this.Animation = CharacterAnimationState.Down;
 }
Example #31
0
        /// <summary>
        /// Forwards a message that comes from the hosted window to the WPF window. This method can be used for example to forward keyboard events.
        /// </summary>
        /// <param name="hwnd">The hwnd of the hosted window.</param>
        /// <param name="msg">The message identifier.</param>
        /// <param name="wParam">The word parameter of the message.</param>
        /// <param name="lParam">The long parameter of the message.</param>
        public void ForwardMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam)
        {
            DispatcherOperation task;

            switch (msg)
            {
            case NativeHelper.WM_RBUTTONDOWN:
                mouseMoveCount = 0;
                task           = Dispatcher.InvokeAsync(() =>
                {
                    RaiseMouseButtonEvent(Mouse.PreviewMouseDownEvent, MouseButton.Right);
                    RaiseMouseButtonEvent(Mouse.MouseDownEvent, MouseButton.Right);
                });
                task.Wait(TimeSpan.FromSeconds(1.0f));
                break;

            case NativeHelper.WM_RBUTTONUP:
                task = Dispatcher.InvokeAsync(() =>
                {
                    RaiseMouseButtonEvent(Mouse.PreviewMouseUpEvent, MouseButton.Right);
                    RaiseMouseButtonEvent(Mouse.MouseUpEvent, MouseButton.Right);
                });
                task.Wait(TimeSpan.FromSeconds(1.0f));
                break;

            case NativeHelper.WM_LBUTTONDOWN:
                task = Dispatcher.InvokeAsync(() =>
                {
                    RaiseMouseButtonEvent(Mouse.PreviewMouseDownEvent, MouseButton.Left);
                    RaiseMouseButtonEvent(Mouse.MouseDownEvent, MouseButton.Left);
                });
                task.Wait(TimeSpan.FromSeconds(1.0f));
                break;

            case NativeHelper.WM_LBUTTONUP:
                task = Dispatcher.InvokeAsync(() =>
                {
                    RaiseMouseButtonEvent(Mouse.PreviewMouseUpEvent, MouseButton.Left);
                    RaiseMouseButtonEvent(Mouse.MouseUpEvent, MouseButton.Left);
                });
                task.Wait(TimeSpan.FromSeconds(1.0f));
                break;

            case NativeHelper.WM_MOUSEMOVE:
                ++mouseMoveCount;
                break;

            case NativeHelper.WM_CONTEXTMENU:
                // TODO: Tracking drag offset would be better, but might be difficult since we replace the mouse to its initial position each time it is moved.
                if (mouseMoveCount < 3)
                {
                    Dispatcher.InvokeAsync(() =>
                    {
                        DependencyObject dependencyObject = this;
                        while (dependencyObject != null)
                        {
                            var element = dependencyObject as FrameworkElement;
                            if (element?.ContextMenu != null)
                            {
                                element.Focus();
                                // Data context will not be properly set if the popup is open this way, so let's set it ourselves
                                element.ContextMenu.SetCurrentValue(DataContextProperty, element.DataContext);
                                element.ContextMenu.IsOpen = true;
                                var source = (HwndSource)PresentationSource.FromVisual(element.ContextMenu);
                                if (source != null)
                                {
                                    source.AddHook(ContextMenuWndProc);
                                    contextMenuPosition = Mouse.GetPosition(this);
                                    lock (contextMenuSources)
                                    {
                                        contextMenuSources.Add(source);
                                    }
                                }
                                break;
                            }
                            dependencyObject = VisualTreeHelper.GetParent(dependencyObject);
                        }
                    });
                }
                break;

            default:
                var parent = NativeHelper.GetParent(hwnd);
                NativeHelper.PostMessage(parent, msg, wParam, lParam);
                break;
            }
        }
Example #32
0
        private void Ink_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (IsSnap)
            {
                if (ISDown == true)
                {
                    System.Windows.Point point = Mouse.GetPosition(this);
                    rect           = new Rect(Startpoint, point);
                    rec.Visibility = Visibility.Visible;
                    rec.Margin     = new Thickness(rect.Left, rect.Top, 0, 0);
                    rec.Height     = rect.Height;
                    rec.Width      = rect.Width;
                    //System.Drawing.Rectangle rc = System.Windows.Forms.SystemInformation.VirtualScreen;
                    //System.Drawing.Rectangle rectangle = new Rectangle((int)rect.X,(int)rect.Y,(int)rect.Width,(int)rect.Height);
                    //var bitmap = new Bitmap((int)rectangle.Width, (int)rectangle.Height);

                    //using (Graphics g = Graphics.FromImage(bitmap))
                    //{

                    //    g.CopyFromScreen((int)rectangle.X, (int)rectangle.Y, 0, 0, rectangle.Size, CopyPixelOperation.SourceCopy);
                    //}

                    //Rect maskrect1 = new Rect(0, 0,SystemInformation.VirtualScreen.Width, rect.Top);
                    //MessageBox.Show(maskrect1.Left.ToString() + '\t' + maskrect1.Top.ToString() + '\t' + maskrect1.Bottom.ToString() + '\t' + maskrect1.Right.ToString());
                    //Rect maskrect2 = new Rect(0, rect.Top, rect.Left, rect.Height);
                    //Rect maskrect3 = new Rect(0, rect.Bottom, SystemInformation.VirtualScreen.Width, SystemInformation.VirtualScreen.Height-rect.Bottom);
                    //Rect maskrect4 = new Rect(rect.Right, rect.Top, SystemInformation.VirtualScreen.Width-rect.Right, rect.Height);

                    //mask1.Margin = new Thickness(0, 0, 0, rect.Top);
                    ////mask1.Height = maskrect1.Height;
                    ////mask1.Width = maskrect1.Width;
                    //mask1.Height = rect.Top;
                    //mask1.Width = SystemInformation.VirtualScreen.Width;
                    //mask2.Margin = new Thickness(maskrect2.Left, maskrect2.Top, maskrect2.Right, maskrect2.Bottom);
                    //mask2.Height = maskrect2.Height;
                    //mask2.Width = maskrect2.Width;
                    //mask3.Margin = new Thickness(maskrect3.Left, maskrect3.Top, maskrect3.Right, maskrect3.Bottom);
                    //mask3.Height = maskrect3.Height;
                    //mask3.Width = maskrect3.Width;
                    //mask4.Margin = new Thickness(maskrect4.Left, maskrect4.Top, maskrect4.Right, maskrect4.Bottom);
                    //mask4.Height = maskrect4.Height;
                    //mask4.Width = maskrect4.Width;
                    //Image image = ScreenShot;


                    //Image img = ScreenShot;
                    //Rectangle dest = new Rectangle((int)snapArea.X, (int)snapArea.Y, (int)snapArea.Width, (int)snapArea.Height);
                    //GraphicsUnit units = GraphicsUnit.Pixel;
                    //Graphics graphics=Graphics.FromImage(img);
                    //graphics.DrawImage(img, dest, (int)snapArea.X, (int)snapArea.Y, (int)snapArea.Width, (int)snapArea.Height, units);

                    // Create rectangle for adjusted image.
                    //Rectangle destRect2 = new Rectangle((int)snapArea.X, (int)snapArea.Y, (int)snapArea.Width, (int)snapArea.Height);

                    // Create image attributes and set large gamma.
                    //ImageAttributes imageAttr = new ImageAttributes();
                    //imageAttr.SetGamma(4.0F);

                    //// Draw adjusted image to screen.
                    //graphics.DrawImage(img, destRect2, (int)snapArea.X, (int)snapArea.Y, (int)snapArea.Width, (int)snapArea.Height, units, imageAttr);

                    //PaintEventArgs paintEventArgs=new PaintEventArgs();
                }
            }
        }
Example #33
0
 /// <summary>
 /// Return the Angle as degrees
 /// </summary>
 static public double getAngle(System.Windows.Point p1, System.Windows.Point p2)
 {
     return(getAngle(p1.X, p1.Y, p2.X, p2.Y));
 }
 public static void drawDimension(Rectangle3d tempBoundingBox, List <FloorPlan.Dimension> dimensions, double tempScaleFactor, System.Windows.Point tempOrigin, ref Canvas UnitPlanCanvas)
 {
     for (int i = 0; i < dimensions.Count; i++)
     {
         FloorPlan.Dimension tempDimension = dimensions[i];
         drawText(tempBoundingBox, tempDimension.NumberText, tempScaleFactor, tempOrigin, ref UnitPlanCanvas, 20, Brushes.Black);
         List <Curve> dimensionCurves = tempDimension.ExtensionLine;
         dimensionCurves.Add(tempDimension.DimensionLine);
         drawPlan(tempBoundingBox, dimensionCurves, tempScaleFactor, tempOrigin, ref UnitPlanCanvas, Brushes.Black, 1);
     }
 }
        public static void drawPlan(Rectangle3d tempBoundingBox, Curve curveToDraw, double tempScaleFactor, System.Windows.Point tempOrigin, ref Canvas UnitPlanCanvas, Brush strokeBrush, double strokeThickness)
        {
            Curve[] shatteredCurves = curveToDraw.DuplicateSegments();

            if (shatteredCurves.Length > 1)
            {
                foreach (Curve j in shatteredCurves)
                {
                    System.Windows.Point Start = pointConverter(tempBoundingBox, j.PointAt(j.Domain.T0), tempScaleFactor, tempOrigin);
                    System.Windows.Point End   = pointConverter(tempBoundingBox, j.PointAt(j.Domain.T1), tempScaleFactor, tempOrigin);

                    System.Windows.Shapes.Line line = new System.Windows.Shapes.Line();
                    line.Stroke = strokeBrush;

                    line.X1 = Math.Abs(Start.X);
                    line.X2 = Math.Abs(End.X);
                    line.Y1 = Math.Abs(Start.Y);
                    line.Y2 = Math.Abs(End.Y);

                    line.StrokeThickness = strokeThickness;

                    UnitPlanCanvas.Children.Add(line);
                }
            }
            else
            {
                if (curveToDraw.PointAt(curveToDraw.Domain.Mid) != (curveToDraw.PointAtStart + curveToDraw.PointAtEnd) / 2)
                {
                    List <Curve> shatteredArc = shatterArc(curveToDraw);

                    foreach (Curve j in shatteredArc)
                    {
                        System.Windows.Point Start = pointConverter(tempBoundingBox, j.PointAt(j.Domain.T0), tempScaleFactor, tempOrigin);
                        System.Windows.Point End   = pointConverter(tempBoundingBox, j.PointAt(j.Domain.T1), tempScaleFactor, tempOrigin);

                        System.Windows.Shapes.Line line = new System.Windows.Shapes.Line();
                        line.Stroke = strokeBrush;

                        line.X1 = Math.Abs(Start.X);
                        line.X2 = Math.Abs(End.X);
                        line.Y1 = Math.Abs(Start.Y);
                        line.Y2 = Math.Abs(End.Y);

                        line.StrokeThickness = strokeThickness;

                        UnitPlanCanvas.Children.Add(line);
                    }
                }
                else
                {
                    System.Windows.Point Start = pointConverter(tempBoundingBox, curveToDraw.PointAt(curveToDraw.Domain.T0), tempScaleFactor, tempOrigin);
                    System.Windows.Point End   = pointConverter(tempBoundingBox, curveToDraw.PointAt(curveToDraw.Domain.T1), tempScaleFactor, tempOrigin);

                    System.Windows.Shapes.Line line = new System.Windows.Shapes.Line();
                    line.Stroke = strokeBrush;

                    line.X1 = Math.Abs(Start.X);
                    line.X2 = Math.Abs(End.X);
                    line.Y1 = Math.Abs(Start.Y);
                    line.Y2 = Math.Abs(End.Y);

                    line.StrokeThickness = strokeThickness;

                    UnitPlanCanvas.Children.Add(line);
                }
            }
        }
Example #36
0
        public virtual double GetNearestParameterFromPoint(System.Windows.Point point)
        {
            var projection = Math.GetProjection(point, Coordinates);

            return(projection.Ratio);
        }
        static void RepaintNodeShapes(Canvas nodeCanvas)
        {
            Border nodeCanvasBorder = (Border)nodeCanvas.Parent;

            RemoveNodeShapes(nodeCanvas);
            NodeCanvasData ncDInst = GetCanvasNodeData(nodeCanvas);
            Node           node    = ncDInst.node;

            Border rectBorder = new Border()
            {
                CornerRadius = new CornerRadius(2), BorderThickness = new Thickness(1), BorderBrush = System.Windows.Media.Brushes.Black
            };

            System.Windows.Shapes.Rectangle heirsPivotRect = new System.Windows.Shapes.Rectangle()
            {
                Stroke = new SolidColorBrush(Colors.Black), Fill = new SolidColorBrush(Colors.IndianRed), Width = 25, Height = 25
            };
            Canvas.SetLeft(rectBorder, Canvas.GetLeft(nodeCanvasBorder) + .5f * nodeCanvasBorder.ActualWidth - 12.5f);
            Canvas.SetTop(rectBorder, Canvas.GetTop(nodeCanvasBorder) + nodeCanvasBorder.ActualHeight);
            heirsPivotRect.MouseEnter           += new MouseEventHandler(canvasRedRect_MouseEnter);
            heirsPivotRect.MouseLeave           += new MouseEventHandler(canvasRedRect_MouseLeave);
            heirsPivotRect.MouseLeftButtonDown  += new MouseButtonEventHandler(canvasRedRect_LeftMouseDown);
            heirsPivotRect.MouseRightButtonDown += new MouseButtonEventHandler(canvasRedRect_RightMouseDown);
            rectBorder.Child = heirsPivotRect;
            workspaceCanvas.Children.Add(rectBorder);
            Canvas.SetZIndex(rectBorder, 10000);
            ncDInst.heirsPivot = heirsPivotRect;

            Ellipse parentPivotEllipse = new Ellipse()
            {
                Stroke = new SolidColorBrush(Colors.Black), Fill = new SolidColorBrush(Colors.CadetBlue), Width = 25, Height = 25
            };

            Canvas.SetLeft(parentPivotEllipse, Canvas.GetLeft(nodeCanvasBorder) + .5f * nodeCanvas.Width - 12.5f);
            Canvas.SetTop(parentPivotEllipse, Canvas.GetTop(nodeCanvasBorder) - 25);
            workspaceCanvas.Children.Add(parentPivotEllipse);
            Canvas.SetZIndex(parentPivotEllipse, 20000);
            ncDInst.parentPivot = parentPivotEllipse;

            if (node.heirs != null && node.heirs.Count > 0)
            {
                List <Canvas> heirsCanvases = new List <Canvas>();
                foreach (Heir heir in node.heirs)
                {
                    heirsCanvases.Add(curNodesOnLayout.Where(el => el.Value.node.Equals(heir.heirNode)).ToArray()[0].Key);
                }
                for (int i = 0; i < heirsCanvases.Count; i++)
                {
                    Border   heirCanvBorder = (Border)heirsCanvases[i].Parent;
                    Polyline newPLine;
                    PointF   p0, p1, p2, p3;
                    p1 = new PointF((float)(Canvas.GetLeft(nodeCanvasBorder) + .5f * nodeCanvasBorder.ActualWidth), (float)(Canvas.GetTop(nodeCanvasBorder) + nodeCanvasBorder.ActualHeight + ncDInst.heirsPivot.ActualHeight * .5f));
                    p2 = new PointF((float)(Canvas.GetLeft(heirCanvBorder) + .5f * (heirCanvBorder).ActualWidth), (float)(Canvas.GetTop(heirCanvBorder) - GetCanvasNodeData(heirsCanvases[i]).parentPivot.ActualHeight * .5f));
                    if (!nodeCanvasBorder.Equals(heirCanvBorder))
                    {
                        p0       = new PointF(p1.X, (float)Canvas.GetTop(nodeCanvasBorder));
                        p3       = new PointF(p2.X, (float)(Canvas.GetTop(heirCanvBorder) + (heirCanvBorder).ActualHeight));
                        newPLine = RelationsDrawer.ConstructPolyline(p0, p1, p2, p3);
                    }
                    else
                    {
                        p0       = new PointF(p1.X, p1.Y - 100f);
                        p3       = new PointF(p2.X, p2.Y + 100f);
                        newPLine = RelationsDrawer.ConstructPolyline(p0, p1, p2, p3, true);
                    }

                    int midIndex = (int)(newPLine.Points.Count * .5f);

                    AddArrowsToPolyline(newPLine);

                    newPLine.MouseEnter += new MouseEventHandler(relation_MouseEnter);
                    newPLine.MouseLeave += new MouseEventHandler(relation_MouseLeave);
                    System.Windows.Point textBlockPos = newPLine.Points.ToArray()[midIndex];

                    Border tmpBorder = (Border)GetBranchTextBlock(nodeCanvas, heirsCanvases[i]).Parent;
                    Canvas.SetLeft(tmpBorder, textBlockPos.X - tmpBorder.ActualWidth * .5f);
                    Canvas.SetTop(tmpBorder, textBlockPos.Y);

                    ncDInst.relations.Add(newPLine);
                    workspaceCanvas.Children.Add(newPLine);
                    Canvas.SetZIndex(newPLine, 0);
                }
            }
        }
Example #38
0
 private void Control_MouseDown(object sender, MouseButtonEventArgs e)
 {
     _dragStartMousePosition          = e.GetPosition(Control);
     _dragStartViewportCenterPosition = Viewport.CenterX;
 }
Example #39
0
        private void DrawBox(Wpg.WordprocessingGroup wordprocessingGroup1, Rect extents, string colour, int thick)
        {
            UInt32Value bondLineId   = UInt32Value.FromUInt32((uint)_ooxmlId++);
            string      bondLineName = "box" + bondLineId;

            Int64Value width1  = OoXmlHelper.ScaleCmlToEmu(extents.Width);
            Int64Value height1 = OoXmlHelper.ScaleCmlToEmu(extents.Height);
            Int64Value top1    = OoXmlHelper.ScaleCmlToEmu(extents.Top);
            Int64Value left1   = OoXmlHelper.ScaleCmlToEmu(extents.Left);
            Point      pp1     = new Point(left1, top1);
            Size       ss2     = new Size(width1, height1);

            pp1.Offset(OoXmlHelper.ScaleCmlToEmu(-_canvasExtents.Left), OoXmlHelper.ScaleCmlToEmu(-_canvasExtents.Top));
            Rect boundingBox = new Rect(pp1, ss2);

            Int64Value width  = (Int64Value)boundingBox.Width;
            Int64Value height = (Int64Value)boundingBox.Height;
            Int64Value top    = (Int64Value)boundingBox.Top;
            Int64Value left   = (Int64Value)boundingBox.Left;

            Wps.WordprocessingShape        wordprocessingShape1        = new Wps.WordprocessingShape();
            Wps.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Wps.NonVisualDrawingProperties()
            {
                Id   = bondLineId,
                Name = bondLineName
            };
            Wps.NonVisualDrawingShapeProperties nonVisualDrawingShapeProperties1 = new Wps.NonVisualDrawingShapeProperties();

            Wps.ShapeProperties shapeProperties1 = new Wps.ShapeProperties();

            A.Transform2D transform2D1 = new A.Transform2D();
            A.Offset      offset2      = new A.Offset()
            {
                X = left, Y = top
            };
            A.Extents extents2 = new A.Extents()
            {
                Cx = width, Cy = height
            };

            transform2D1.Append(offset2);
            transform2D1.Append(extents2);

            A.CustomGeometry  customGeometry1  = new A.CustomGeometry();
            A.AdjustValueList adjustValueList1 = new A.AdjustValueList();
            A.Rectangle       rectangle1       = new A.Rectangle()
            {
                Left = "l", Top = "t", Right = "r", Bottom = "b"
            };

            A.PathList pathList1 = new A.PathList();

            A.Path path1 = new A.Path()
            {
                Width = width, Height = height
            };

            // Starting Point
            A.MoveTo moveTo1 = new A.MoveTo();
            A.Point  point1  = new A.Point()
            {
                X = "0", Y = "0"
            };
            moveTo1.Append(point1);

            // Mid Point
            A.LineTo lineTo1 = new A.LineTo();
            A.Point  point2  = new A.Point()
            {
                X = boundingBox.Width.ToString("0"), Y = "0"
            };
            lineTo1.Append(point2);

            // Mid Point
            A.LineTo lineTo2 = new A.LineTo();
            A.Point  point3  = new A.Point()
            {
                X = boundingBox.Width.ToString("0"), Y = boundingBox.Height.ToString("0")
            };
            lineTo2.Append(point3);

            // Last Point
            A.LineTo lineTo3 = new A.LineTo();
            A.Point  point4  = new A.Point()
            {
                X = "0", Y = boundingBox.Height.ToString("0")
            };
            lineTo3.Append(point4);

            // Back to Start Point
            A.LineTo lineTo4 = new A.LineTo();
            A.Point  point5  = new A.Point()
            {
                X = "0", Y = "0"
            };
            lineTo4.Append(point5);

            path1.Append(moveTo1);
            path1.Append(lineTo1);
            path1.Append(lineTo2);
            path1.Append(lineTo3);
            path1.Append(lineTo4);

            pathList1.Append(path1);

            customGeometry1.Append(adjustValueList1);
            customGeometry1.Append(rectangle1);
            customGeometry1.Append(pathList1);

            A.Outline outline1 = new A.Outline()
            {
                Width = thick, CapType = A.LineCapValues.Round
            };

            A.SolidFill solidFill1 = new A.SolidFill();

            A.RgbColorModelHex rgbColorModelHex1 = new A.RgbColorModelHex()
            {
                Val = colour
            };
            A.Alpha alpha1 = new A.Alpha()
            {
                Val = new Int32Value()
                {
                    InnerText = "100%"
                }
            };

            rgbColorModelHex1.Append(alpha1);

            solidFill1.Append(rgbColorModelHex1);

            outline1.Append(solidFill1);

            shapeProperties1.Append(transform2D1);
            shapeProperties1.Append(customGeometry1);
            shapeProperties1.Append(outline1);

            Wps.ShapeStyle  shapeStyle1    = new Wps.ShapeStyle();
            A.LineReference lineReference1 = new A.LineReference()
            {
                Index = (UInt32Value)0U
            };
            A.FillReference fillReference1 = new A.FillReference()
            {
                Index = (UInt32Value)0U
            };
            A.EffectReference effectReference1 = new A.EffectReference()
            {
                Index = (UInt32Value)0U
            };
            A.FontReference fontReference1 = new A.FontReference()
            {
                Index = A.FontCollectionIndexValues.Minor
            };

            shapeStyle1.Append(lineReference1);
            shapeStyle1.Append(fillReference1);
            shapeStyle1.Append(effectReference1);
            shapeStyle1.Append(fontReference1);
            Wps.TextBodyProperties textBodyProperties1 = new Wps.TextBodyProperties();

            wordprocessingShape1.Append(nonVisualDrawingProperties1);
            wordprocessingShape1.Append(nonVisualDrawingShapeProperties1);
            wordprocessingShape1.Append(shapeProperties1);
            wordprocessingShape1.Append(shapeStyle1);
            wordprocessingShape1.Append(textBodyProperties1);

            wordprocessingGroup1.Append(wordprocessingShape1);
        }
Example #40
0
        private void DrawShape(Wpg.WordprocessingGroup wordprocessingGroup1, Rect extents, A.ShapeTypeValues shape, string colour)
        {
            UInt32Value bondLineId   = UInt32Value.FromUInt32((uint)_ooxmlId++);
            string      bondLineName = "shape" + bondLineId;

            Int64Value width1  = OoXmlHelper.ScaleCmlToEmu(extents.Width);
            Int64Value height1 = OoXmlHelper.ScaleCmlToEmu(extents.Height);
            Int64Value top1    = OoXmlHelper.ScaleCmlToEmu(extents.Top);
            Int64Value left1   = OoXmlHelper.ScaleCmlToEmu(extents.Left);
            Point      pp1     = new Point(left1, top1);
            Size       ss2     = new Size(width1, height1);

            pp1.Offset(OoXmlHelper.ScaleCmlToEmu(-_canvasExtents.Left), OoXmlHelper.ScaleCmlToEmu(-_canvasExtents.Top));
            Rect boundingBox = new Rect(pp1, ss2);

            Int64Value width  = (Int64Value)boundingBox.Width;
            Int64Value height = (Int64Value)boundingBox.Height;
            Int64Value top    = (Int64Value)boundingBox.Top;
            Int64Value left   = (Int64Value)boundingBox.Left;

            A.Extents        extents2        = null;
            A.PresetGeometry presetGeometry1 = null;
            extents2 = new A.Extents()
            {
                Cx = width, Cy = height
            };
            presetGeometry1 = new A.PresetGeometry()
            {
                Preset = shape
            };

            Wps.WordprocessingShape        wordprocessingShape1        = new Wps.WordprocessingShape();
            Wps.NonVisualDrawingProperties nonVisualDrawingProperties1 = new Wps.NonVisualDrawingProperties()
            {
                Id   = bondLineId,
                Name = bondLineName
            };

            Wps.NonVisualDrawingShapeProperties nonVisualDrawingShapeProperties1 = new Wps.NonVisualDrawingShapeProperties();
            //A.ShapeLocks shapeLocks = new A.ShapeLocks()
            //{
            //    NoMove = true,
            //    NoSelection = true
            //};
            //nonVisualDrawingShapeProperties1.Append(shapeLocks);

            Wps.ShapeProperties shapeProperties1 = new Wps.ShapeProperties();

            A.Transform2D transform2D1 = new A.Transform2D();
            A.Offset      offset2      = new A.Offset()
            {
                X = left, Y = top
            };

            transform2D1.Append(offset2);
            transform2D1.Append(extents2);

            A.AdjustValueList adjustValueList1 = new A.AdjustValueList();

            presetGeometry1.Append(adjustValueList1);
            A.SolidFill solidFill1 = new A.SolidFill();

            A.RgbColorModelHex rgbColorModelHex1 = new A.RgbColorModelHex()
            {
                Val = colour
            };
            A.Alpha alpha1 = new A.Alpha()
            {
                Val = new Int32Value()
                {
                    InnerText = "100%"
                }
            };
            solidFill1.Append(rgbColorModelHex1);

            shapeProperties1.Append(transform2D1);
            shapeProperties1.Append(presetGeometry1);
            shapeProperties1.Append(solidFill1);

            Wps.ShapeStyle  shapeStyle1    = new Wps.ShapeStyle();
            A.LineReference lineReference1 = new A.LineReference()
            {
                Index = (UInt32Value)0U
            };
            A.FillReference fillReference1 = new A.FillReference()
            {
                Index = (UInt32Value)0U
            };
            A.EffectReference effectReference1 = new A.EffectReference()
            {
                Index = (UInt32Value)0U
            };
            A.FontReference fontReference1 = new A.FontReference()
            {
                Index = A.FontCollectionIndexValues.Minor
            };

            shapeStyle1.Append(lineReference1);
            shapeStyle1.Append(fillReference1);
            shapeStyle1.Append(effectReference1);
            shapeStyle1.Append(fontReference1);
            Wps.TextBodyProperties textBodyProperties1 = new Wps.TextBodyProperties();

            wordprocessingShape1.Append(nonVisualDrawingProperties1);
            wordprocessingShape1.Append(nonVisualDrawingShapeProperties1);
            wordprocessingShape1.Append(shapeProperties1);
            wordprocessingShape1.Append(shapeStyle1);
            wordprocessingShape1.Append(textBodyProperties1);

            wordprocessingGroup1.Append(wordprocessingShape1);
        }
Example #41
0
        private void ShrinkBondLines(Progress pb)
        {
            // so that they do not overlap label characters

            if (_chemistryModel.AllAtoms.Count > 1)
            {
                pb.Show();
            }
            pb.Message = "Clipping Bond Lines";
            pb.Value   = 0;
            //pb.Maximum = (m_AtomLabelCharacters.Count * m_BondLines.Count);
            pb.Maximum = _atomLabelCharacters.Count;

            foreach (AtomLabelCharacter alc in _atomLabelCharacters)
            {
                pb.Increment(1);

                double width  = OoXmlHelper.ScaleCsTtfToCml(alc.Character.Width);
                double height = OoXmlHelper.ScaleCsTtfToCml(alc.Character.Height);

                if (alc.IsSubScript)
                {
                    // Shrink bounding box
                    width  = width * OoXmlHelper.SUBSCRIPT_SCALE_FACTOR;
                    height = height * OoXmlHelper.SUBSCRIPT_SCALE_FACTOR;
                }

                // Create rectangle of the bounding box with a suitable clipping margin
                Rect cbb = new Rect(alc.Position.X - OoXmlHelper.CHARACTER_CLIPPING_MARGIN,
                                    alc.Position.Y - OoXmlHelper.CHARACTER_CLIPPING_MARGIN,
                                    width + (OoXmlHelper.CHARACTER_CLIPPING_MARGIN * 2),
                                    height + (OoXmlHelper.CHARACTER_CLIPPING_MARGIN * 2));

                //Debug.WriteLine("Character: " + alc.Ascii + " Rectangle: " + a);

                // Just in case we end up splitting a line into two
                List <BondLine> extraBondLines = new List <BondLine>();

                // Select Lines which may require trimming
                // By using LINQ to implement the following SQL
                // Where (L.Right Between Cbb.Left And Cbb.Right)
                //    Or (L.Left Between Cbb.Left And Cbb.Right)
                //    Or (L.Top Between Cbb.Top And Cbb.Botton)
                //    Or (L.Bottom Between Cbb.Top And Cbb.Botton)

                var targeted = from l in _bondLines
                               where (cbb.Left <= l.BoundingBox.Right & l.BoundingBox.Right <= cbb.Right)
                               | (cbb.Left <= l.BoundingBox.Left & l.BoundingBox.Left <= cbb.Right)
                               | (cbb.Top <= l.BoundingBox.Top & l.BoundingBox.Top <= cbb.Bottom)
                               | (cbb.Top <= l.BoundingBox.Bottom & l.BoundingBox.Bottom <= cbb.Bottom)
                               select l;

                foreach (BondLine bl in targeted)
                {
                    //pb.Increment(1);

                    Point start = new Point(bl.Start.X, bl.Start.Y);
                    Point end   = new Point(bl.End.X, bl.End.Y);

                    //Debug.WriteLine("  Line From: " + start + " To: " + end);

                    int attempts = 0;
                    if (CohenSutherland.ClipLine(cbb, ref start, ref end, out attempts))
                    {
                        //Debug.WriteLine("    Clipped Line Start Point: " + start);
                        //Debug.WriteLine("    Clipped Line   End Point: " + end);

                        bool bClipped = false;

                        if (Math.Abs(bl.Start.X - start.X) < EPSILON && Math.Abs(bl.Start.Y - start.Y) < EPSILON)
                        {
                            bl.Start = new Point(end.X, end.Y);
                            bClipped = true;
                        }
                        if (Math.Abs(bl.End.X - end.X) < EPSILON && Math.Abs(bl.End.Y - end.Y) < EPSILON)
                        {
                            bl.End   = new Point(start.X, start.Y);
                            bClipped = true;
                        }

                        if (!bClipped)
                        {
                            // Line was clipped at both ends;
                            // 1. Generate new line
                            BondLine extraLine = new BondLine(new Point(end.X, end.Y), new Point(bl.End.X, bl.End.Y), bl.Type, bl.Parent);
                            extraBondLines.Add(extraLine);
                            // 2. Trim existing line
                            bl.End = new Point(start.X, start.Y);
                        }
                    }
                    if (attempts >= 15)
                    {
                        Debug.WriteLine("Clipping failed !");
                    }
                }

                // Add any extra lines generated by this character into the List of Bond Lines
                foreach (BondLine bl in extraBondLines)
                {
                    _bondLines.Add(bl);
                }
            }
        }
Example #42
0
        public OoXmlRenderer(Model.Model model, Options options, IChem4WordTelemetry telemetry, Point topLeft)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            _options   = options;
            _telemetry = telemetry;
            _topLeft   = topLeft;

            _telemetry.Write(module, "Verbose", "Called");

            LoadFont();

            _chemistryModel = model;

            DetermineInitialExtents();
        }
 /// <summary>
 /// 标记鼠标点击坐标
 /// </summary>
 /// <param name="cv"></param>
 private void MarkMousePosition(Canvas cv)
 {
     mousePosition = Mouse.GetPosition(cv);
 }
Example #44
0
        protected override void DropOnto(System.Windows.Point pt)
        {
            // handle dropped "Instrument"s by adding them to the Link's LabelNode (a Group)
            // and by remembering the position of the label relative to a segment of the Link.Route
            var newlabs = this.Diagram.SelectedParts.OfType <Node>().Where(n => Labelable(n)).ToList();

            if (newlabs.Count() > 0)
            {
                // see if the user is dropping onto a Link
                Link overlink = this.Diagram.Panel.FindElementAt <Link>(pt, Part.FindAncestor <Link>, p => ConsiderDragOver(pt, p), SearchLayers.Links);
                if (overlink != null)
                {
                    PipeData linkdata = overlink.Data as PipeData;
                    MyModel  model    = this.Diagram.Model as MyModel;
                    if (linkdata != null && model != null)
                    {
                        // get link's existing label group
                        ItemData labelgroup = model.GetLabelNodeForLink(linkdata);
                        if (labelgroup == null) // create it if it doesn't have one already
                        {
                            labelgroup = new InstrumentData()
                            {
                                Key = "LG", IsSubGraph = true
                            };
                            model.AddNode(labelgroup); // will provide unique Key for new group
                            model.SetLinkLabelKey(linkdata, labelgroup.Key);
                        }
                        // add each dropped label to link's label group
                        foreach (Node lab in newlabs)
                        {
                            ItemData labdata = lab.Data as ItemData;
                            if (labdata != null)
                            {
                                model.SetGroupNodeKey(labdata, labelgroup.Key);
                            }
                        }
                    }
                }
                // find closest segment for each label node and remember it and its offset
                foreach (Node lab in newlabs)
                {
                    InstrumentData labdata = lab.Data as InstrumentData;
                    if (labdata == null)
                    {
                        continue;
                    }
                    Group labcoll = lab.ContainingSubGraph;
                    if (labcoll == null)
                    {
                        continue;
                    }
                    Link link = labcoll.LabeledLink;
                    if (link != null)
                    {
                        Point labc = new Point(lab.Bounds.X + lab.Bounds.Width / 2, lab.Bounds.Y + lab.Bounds.Height / 2);
                        var   pts  = link.Route.Points;
                        if (pts.Count < 2)
                        {
                            continue;
                        }
                        int idx = link.Route.FindClosestSegment(labc);
                        if (idx >= pts.Count - 1)
                        {
                            idx = pts.Count - 2;
                        }
                        labdata.Index = idx;
                        Point a = pts[idx];
                        Point b = pts[idx + 1];
                        if (Math.Abs(a.Y - b.Y) < 0.1)
                        {
                            if (a.X < b.X)
                            {
                                labdata.Fraction = (labc.X <= a.X ? 0 : (labc.X >= b.X ? 1 : (labc.X - a.X) / (b.X - a.X)));
                                labdata.Location = new Point(0, labc.Y - a.Y);
                            }
                            else
                            {
                                labdata.Fraction = (labc.X >= a.X ? 0 : (labc.X <= b.X ? 1 : (labc.X - a.X) / (b.X - a.X)));
                                labdata.Location = new Point(0, a.Y - labc.Y);
                            }
                        }
                        else
                        {
                            if (a.Y < b.Y)
                            {
                                labdata.Fraction = (labc.Y <= a.Y ? 0 : (labc.Y >= b.Y ? 1 : (labc.Y - a.Y) / (b.Y - a.Y)));
                                labdata.Location = new Point(0, a.X - labc.X);
                            }
                            else
                            {
                                labdata.Fraction = (labc.Y >= a.Y ? 0 : (labc.Y <= b.Y ? 1 : (labc.Y - a.Y) / (b.Y - a.Y)));
                                labdata.Location = new Point(0, labc.X - a.X);
                            }
                        }
                    }
                }
            }
            else
            {
                // rotate dropped "Valve"s
                newlabs = this.Diagram.SelectedParts.OfType <Node>().Where(n => Spliceable(n)).ToList();
                if (newlabs.Count() > 0)
                {
                    // see if the user is dropping onto a Link
                    Link    overlink = this.Diagram.Panel.FindElementAt <Link>(pt, Part.FindAncestor <Link>, p => ConsiderDragOver(pt, p), SearchLayers.Links);
                    MyModel model    = this.Diagram.Model as MyModel;
                    if (overlink != null && model != null)
                    {
                        // get the data representing a Pipe
                        PipeData oldlinkdata = overlink.Data as PipeData;
                        // get the Group holding Instruments for the Pipe, if any
                        ItemData labelgroup = model.GetLabelNodeForLink(oldlinkdata);
                        var      pts        = overlink.Route.Points;
                        if (pts.Count >= 2)
                        {
                            // maybe rotate the Valve nodes
                            foreach (Node lab in newlabs)
                            {
                                Point labc = new Point(lab.Bounds.X + lab.Bounds.Width / 2, lab.Bounds.Y + lab.Bounds.Height / 2);
                                int   idx  = overlink.Route.FindClosestSegment(labc);
                                if (idx >= pts.Count - 1)
                                {
                                    idx = pts.Count - 2;
                                }
                                Point a = pts[idx];
                                Point b = pts[idx + 1];
                                // if the valve were bi-directional, this needs to be smarter?
                                int angle = 0;
                                if (Math.Abs(a.Y - b.Y) < 0.1) // horizontal
                                {
                                    angle = (a.X < b.X ? 0 : 180);
                                }
                                else
                                {
                                    angle = (a.Y < b.Y ? 90 : 270);
                                }
                                lab.RotationAngle = angle;
                                // the StackPanel.Orientation governs the relative position of the TextBlock;
                                // it is bound to the Node.RotationAngle using a ValveOrientationConverter
                            }
                        }
                        base.DropOnto(pt); // this will splice the Valve(s) into the Link
                        if (oldlinkdata != null)
                        {
                            // find one of the new Pipes
                            PipeData newlinkdata = model.GetFromLinksForNode(newlabs.First().Data as ItemData).First();
                            // this is the label group holding all of the Instruments of the original Link
                            if (labelgroup != null)
                            {
                                // attach the old group of Instruments to the new Pipe
                                model.AddNode(labelgroup);
                                model.SetLinkLabelKey(newlinkdata, labelgroup.Key);
                            }
                        }
                    }
                }
                else // handle regular nodes
                {
                    base.DropOnto(pt);
                }
            }
        }
 public Shape drawLineDashRed(win.Point inicio, win.Point fim)
 {
     return(drawLineDashRed(inicio.X, inicio.Y, fim.X, fim.Y));
 }
 public Shape drawLine(win.Point start, win.Point end)
 {
     return(drawLine(start.X, start.Y, end.X, end.Y));
 }
 private static void SetMousePosition(ToolTip tooltip, FrameworkElement parent, Point currentPos)
 {
     tooltip.Placement        = PlacementMode.Relative;
     tooltip.HorizontalOffset = currentPos.X + OffsetX + (int)tooltip.GetValue(OffsetXProperty) + (int)parent.GetValue(OffsetXProperty);
     tooltip.VerticalOffset   = currentPos.Y + (int)tooltip.GetValue(OffsetYProperty) + (int)parent.GetValue(OffsetYProperty);
 }
        private void imgResult_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            String ResultText;

            System.Windows.Point Position = e.GetPosition(imgResult);

            lstResults.Items.Clear();

            foreach (PageComponent Component in m_OCR.PageImage.Components)
            {
                if (Component.Area.Contains((int)Position.X, (int)Position.Y))
                {
                    ExtractFeatures.CreateCompareMatrixWithoutPruning(Component, Component.Bytes);

                    imgOriginal.Bytes = Component.CompareMatrix;
                    for (int index = 0; index < 256; index++)
                    {
                        imgOriginal.GridBrushes[index] = new SolidColorBrush(System.Windows.Media.Color.FromRgb((byte)index, (byte)index, (byte)index));
                    }
                    imgOriginal.InvalidateVisual();


                    //Add thinned and stroked image
                    //Merge strokematrix and pixeltypematrix to show all info in the same image
                    for (int x = 0; x < 32; x++)
                    {
                        for (int y = 0; y < 32; y++)
                        {
                            if (Component.PixelTypeMatrix[x, y] == ePixelType.End)
                            {
                                Component.StrokeMatrix[x, y] = 0xFE;
                            }
                            if (Component.PixelTypeMatrix[x, y] == ePixelType.Junction)
                            {
                                Component.StrokeMatrix[x, y] = 0xFD;
                            }
                            if (Component.StrokeMatrix[x, y] == 0xFF)
                            {
                                if (Component.CompareMatrix[x, y] != 0xFF)
                                {
                                    Component.StrokeMatrix[x, y] = 0x04;
                                }
                            }
                        }
                    }

                    imgProjection.Bytes            = Component.StrokeMatrix;
                    imgProjection.GridBrushes[4]   = new SolidColorBrush(Colors.LightGray);
                    imgProjection.GridBrushes[11]  = new SolidColorBrush(Colors.Brown);
                    imgProjection.GridBrushes[12]  = new SolidColorBrush(Colors.Maroon);
                    imgProjection.GridBrushes[13]  = new SolidColorBrush(Colors.Magenta);
                    imgProjection.GridBrushes[14]  = new SolidColorBrush(Colors.Lime);
                    imgProjection.GridBrushes[15]  = new SolidColorBrush(Colors.LightCyan);
                    imgProjection.GridBrushes[16]  = new SolidColorBrush(Colors.Purple);
                    imgProjection.GridBrushes[32]  = new SolidColorBrush(Colors.Blue);
                    imgProjection.GridBrushes[48]  = new SolidColorBrush(Colors.Green);
                    imgProjection.GridBrushes[64]  = new SolidColorBrush(Colors.Yellow);
                    imgProjection.GridBrushes[253] = new SolidColorBrush(Colors.Red);
                    imgProjection.GridBrushes[254] = new SolidColorBrush(Colors.Red);

                    imgProjection.InvalidateVisual();

                    //Add result
                    if (Component.RecognitionResults.Count > 0)
                    {
                        ResultText  = Component.RecognitionResults[0].Content;
                        ResultText += " (";
                        ResultText += Component.RecognitionResults[0].Probability;
                        ResultText += " )";
                        lstResults.Items.Add(ResultText);
                    }
                    else
                    {
                        lstResults.Items.Add("No results");
                    }

                    //Add ID
                    labelID.Content    = "ID: " + Component.ID;
                    CurrentComponentId = Component.ID;
                }
            }
        }
Example #49
0
 public static Point ToXwtPoint(this SW.Point point)
 {
     return(new Point(point.X, point.Y));
 }
Example #50
0
 private bool IsOutsideGrid(Point point)
 {
     return(point.X <= 0 || point.Y <= 0 ||
            point.X + MouseClick.ActualWidth / 2 >= Grid.ActualWidth ||
            point.Y + MouseClick.ActualHeight / 2 >= Grid.ActualHeight);
 }
        private void moveIn(object sender, EventArgs e)
        {
            Int32 pageSwitchType = dPage.pageSwitchType;

            if (isBack && backPageSwitchType > 0)
            {
                pageSwitchType = backPageSwitchType;
            }
            if (pageSwitchType <= 0)
            {
                pageSwitchType = 1;
            }
            int pageWidth = dPage.width;

            if (pageWidth <= 0)
            {
                pageWidth = App.localStorage.cfg.screenWidth;
            }


            //1.默认
            if (pageSwitchType == 1)
            {
                mainFrame.Background = Brushes.Transparent;
                return;
            }
            //2.淡入
            else if (pageSwitchType == 2)
            {
                TransformGroup group = new TransformGroup();
                RenderTransform = group;
                DoubleAnimation da = new DoubleAnimation(0, 1.0, new Duration(TimeSpan.FromMilliseconds(400)));
                da.BeginTime = TimeSpan.FromMilliseconds(0);
                IEasingFunction easingFunction = new SineEase()
                {
                    EasingMode = EasingMode.EaseOut
                };
                da.EasingFunction = easingFunction;
                da.Completed     += a2_Completed;
                BeginAnimation(UIElement.OpacityProperty, da);
                return;
            }

            //3.右侧移入
            else if (pageSwitchType == 3)
            {
                if (isBack)
                {
                    return;
                }



                TransformGroup group = new TransformGroup();
                RenderTransform = group;

                double             middlePos          = pageWidth / 2;
                TranslateTransform translateTransform = TransformGroupUtil.GetTranslateTransform(group);
                DoubleAnimation    da = new DoubleAnimation(middlePos, 0, new Duration(TimeSpan.FromMilliseconds(500)));
                da.BeginTime = TimeSpan.FromMilliseconds(0);
                IEasingFunction easingFunction = new SineEase()
                {
                    EasingMode = EasingMode.EaseOut
                };
                da.AccelerationRatio = 0.9;
                //  da.EasingFunction = easingFunction;
                da.Completed += a2_Completed;
                translateTransform.BeginAnimation(TranslateTransform.XProperty, da);


                Opacity = 0;
                DoubleAnimation da1 = new DoubleAnimation(0, 1.0, new Duration(TimeSpan.FromMilliseconds(100)));
                da1.BeginTime      = TimeSpan.FromMilliseconds(0);
                da1.EasingFunction = easingFunction;
                BeginAnimation(UIElement.OpacityProperty, da1);
                return;
            }

            //4.右侧拉伸
            else if (pageSwitchType == 4)
            {
                if (isBack)
                {
                    return;
                }
                RenderTransformOrigin = new System.Windows.Point(1, 0);
                TransformGroup group = new TransformGroup();
                RenderTransform = group;

                ScaleTransform  scaleTransform = TransformGroupUtil.GetScaleTransform(group);
                DoubleAnimation da             = new DoubleAnimation(0, 1.0, new Duration(TimeSpan.FromMilliseconds(500)));
                da.BeginTime = TimeSpan.FromMilliseconds(0);
                //da.EasingFunction = easingFunction;
                da.Completed += a2_Completed;
                scaleTransform.BeginAnimation(ScaleTransform.ScaleXProperty, da);
                return;
            }

            //5.中心放大
            else if (pageSwitchType == 5)
            {
                if (isBack)
                {
                    return;
                }
                RenderTransformOrigin = new System.Windows.Point(0.5, 0.5);
                TransformGroup group = new TransformGroup();
                RenderTransform = group;


                ScaleTransform  scaleTransform = TransformGroupUtil.GetScaleTransform(group);
                DoubleAnimation da             = new DoubleAnimation(0.2, 1.0, new Duration(TimeSpan.FromMilliseconds(500)));
                da.BeginTime = TimeSpan.FromMilliseconds(0);
                IEasingFunction easingFunction = new SineEase()
                {
                    EasingMode = EasingMode.EaseOut
                };
                da.EasingFunction = easingFunction;
                da.Completed     += a2_Completed;
                scaleTransform.BeginAnimation(ScaleTransform.ScaleXProperty, da);
                scaleTransform.BeginAnimation(ScaleTransform.ScaleYProperty, da);


                Opacity = 0;
                DoubleAnimation da1 = new DoubleAnimation(0, 1.0, new Duration(TimeSpan.FromMilliseconds(100)));
                da1.BeginTime      = TimeSpan.FromMilliseconds(0);
                da1.EasingFunction = easingFunction;
                BeginAnimation(UIElement.OpacityProperty, da1);
                return;
            }
        }
Example #52
0
 public MinimizeEventArgs(IDevice d, MinimizeEventType t, Point p)
 {
     Device    = d;
     EventType = t;
     Position  = p;
 }
Example #53
0
        private void InitTextbox(Point mousePoint)
        {
            if (textBox == null)
            {
                textBox = new TextBox
                {
                    MinWidth        = 100,
                    BorderThickness = new Thickness(1),
                    Background      = new SolidColorBrush(Colors.Transparent),
                    AcceptsReturn   = true,
                    FontFamily      = new FontFamily("Microsoft YaHei")
                };
                textBox.LostFocus += (sender, args) =>
                {
                    if (sender is TextBox box)
                    {
                        box.SelectionLength = 0;
                        box.BorderThickness = new Thickness(0);
                        box.IsReadOnly      = true;
                        _istextboxEditing   = false;
                        if (textBox == box && string.IsNullOrEmpty(box.Text))
                        {
                            AdornerRectangle.Children.Remove(box);
                            textBox = null;
                        }
                    }
                };
                textBox.GotFocus += (sender, args) =>
                {
                    if (sender is TextBox box)
                    {
                        box.BorderThickness = new Thickness(1);
                    }
                };
                textBox.MouseDoubleClick += (sender, args) =>
                {
                    if (sender is TextBox box)
                    {
                        _istextboxEditing = true;
                        box.IsReadOnly    = false;
                        box.Cursor        = Cursors.Arrow;
                        box.Focus();
                        box.SelectionLength = 0;
                    }
                };
                textBox.MouseEnter += (sender, args) =>
                {
                    if (sender is TextBox box)
                    {
                        box.Cursor = box.IsReadOnly ? Cursors.SizeAll : Cursors.Arrow;
                    }
                };
                textBox.PreviewMouseLeftButtonDown += (sender, args) =>
                {
                    _selectedElement = (TextBox)sender;
                };
                AdornerRectangle.Children.Add(textBox);
            }

            if (string.IsNullOrEmpty(textBox.Text))
            {
                textBox.MaxWidth    = AdornerRectangle.RenderSize.Width - mousePoint.X;
                textBox.MaxHeight   = AdornerRectangle.RenderSize.Height - mousePoint.Y;
                textBox.BorderBrush = new SolidColorBrush(ColorSelected);
                textBox.Foreground  = new SolidColorBrush(ColorSelected);
                textBox.CaretBrush  = new SolidColorBrush(ColorSelected);
                textBox.FontSize    = SizeSelected * 3;

                Canvas.SetLeft(textBox, mousePoint.X);
                Canvas.SetTop(textBox, mousePoint.Y);
                textBox.Focus();
                textBox.IsReadOnly = false;
            }
            else
            {
                textBox = null;
            }
        }
Example #54
0
 private void UpdateMouseClickPosition(Point position)
 {
     MouseClick.Margin = new Thickness(position.X - MouseClick.ActualWidth / 2, position.Y - MouseClick.ActualHeight / 2, 0, 0);
 }
 internal PointData(double x, double y, double z)
 {
     Position = new Point3D(x, y, z);
     Tex      = new System.Windows.Point(0, 0);
     Normals  = new List <Vector3D>();
 }
Example #56
0
 /// <summary>
 /// 鼠标拖动
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 void MouseDrag(object sender, EventArgs e)
 {
     ballPosition = Mouse.GetPosition(this.canvas_Seat);
     transform.X  = ballPosition.X - mouseFocus.X;
     transform.Y  = ballPosition.Y - mouseFocus.Y;
 }
Example #57
0
 private System.Collections.Generic.IEnumerable <System.Windows.Point> CreatePoints(System.Windows.Point start, System.Windows.Point end, double offset, int count)
 {
     for (int i = 0; i < count; i++)
     {
         yield return(new System.Windows.Point(start.X + (double)i * offset, start.Y - (((i + 1) % 2 == 0) ? offset : 0.0)));
     }
     yield break;
 }
Example #58
0
        /// <summary>
        /// 拖动选择大小
        /// </summary>
        private void ResizeImage(Point mousePoint, Handle handle)
        {
            RectangleGeometry clip = Image.Clip as RectangleGeometry;

            if (clip == null)
            {
                return;
            }

            var clipRect = clip.Rect;

            double rectWidth  = mousePoint.X - x;
            double rectHeight = mousePoint.Y - y;

            var rect_x      = clipRect.X + rectWidth;
            var rect_y      = clipRect.Y + rectHeight;
            var rect_width  = Math.Max(0, clipRect.Width + rectWidth);
            var rect_height = Math.Max(0, clipRect.Height + rectHeight);

            if (handle.Location == ThumbLocation.LeftCenter || handle.Location == ThumbLocation.BottomLeft ||
                handle.Location == ThumbLocation.TopLeft)
            {
                rect_width = Math.Max(0, clipRect.Width - rectWidth);
                rect_x     = Math.Min(rect_x, clipRect.Right);
            }
            if (handle.Location == ThumbLocation.TopLeft || handle.Location == ThumbLocation.TopCenter ||
                handle.Location == ThumbLocation.TopRight)
            {
                rect_height = Math.Max(0, clipRect.Height - rectHeight);
                rect_y      = Math.Min(rect_y, clipRect.Bottom);
            }


            Rect rect = Rect.Empty;

            switch (handle.Location)
            {
            case ThumbLocation.BottomCenter:
                rect = new Rect(clipRect.Location, new Size(clipRect.Width, rect_height));
                break;

            case ThumbLocation.BottomLeft:
                rect = new Rect(new Point(rect_x, clipRect.Location.Y), new Size(rect_width, rect_height));
                break;

            case ThumbLocation.BottomRight:
                rect = new Rect(clipRect.Location, new Size(rect_width, rect_height));
                break;

            case ThumbLocation.LeftCenter:
                rect = new Rect(new Point(rect_x, clipRect.Location.Y), new Size(rect_width, clipRect.Height));
                break;

            case ThumbLocation.RightCenter:
                rect = new Rect(clipRect.Location, new Size(rect_width, clipRect.Height));
                break;

            case ThumbLocation.TopLeft:
                rect = new Rect(new Point(rect_x, rect_y), new Size(rect_width, rect_height));
                break;

            case ThumbLocation.TopCenter:
                rect = new Rect(new Point(clipRect.Location.X, rect_y), new Size(clipRect.Width, rect_height));
                break;

            case ThumbLocation.TopRight:
                rect = new Rect(new Point(clipRect.Location.X, rect_y), new Size(rect_width, rect_height));
                break;
            }

            if (rect != Rect.Empty)
            {
                SetImage(rect);

                UpdateXY(rect.Width > 0, rect.Height > 0);
            }
        }
Example #59
0
        public static Bitmap CaptureImageCursor(ref Point point, double scale)
        {
            try
            {
                var cursorInfo = new CursorInfo();
                cursorInfo.cbSize = Marshal.SizeOf(cursorInfo);

                if (!GetCursorInfo(out cursorInfo))
                {
                    return(null);
                }

                if (cursorInfo.flags != CursorShowing)
                {
                    return(null);
                }

                var hicon = CopyIcon(cursorInfo.hCursor);
                if (hicon == IntPtr.Zero)
                {
                    return(null);
                }

                Iconinfo iconInfo;
                if (!GetIconInfo(hicon, out iconInfo))
                {
                    DeleteObject(hicon);
                    return(null);
                }

                point.X = cursorInfo.ptScreenPos.X - iconInfo.xHotspot;
                point.Y = cursorInfo.ptScreenPos.Y - iconInfo.yHotspot;

                using (var maskBitmap = Image.FromHbitmap(iconInfo.hbmMask))
                {
                    //Is this a monochrome cursor?
                    if (maskBitmap.Height == maskBitmap.Width * 2 && iconInfo.hbmColor == IntPtr.Zero)
                    {
                        var final     = new Bitmap(maskBitmap.Width, maskBitmap.Width);
                        var hDesktop  = GetDesktopWindow();
                        var dcDesktop = GetWindowDC(hDesktop);

                        using (var resultGraphics = Graphics.FromImage(final))
                        {
                            var resultHdc = resultGraphics.GetHdc();
                            var offsetX   = (int)((point.X + 3) * scale);
                            var offsetY   = (int)((point.Y + 3) * scale);

                            BitBlt(resultHdc, 0, 0, final.Width, final.Height, dcDesktop, offsetX, offsetY, CopyPixelOperation.SourceCopy);
                            DrawIconEx(resultHdc, 0, 0, cursorInfo.hCursor, 0, 0, 0, IntPtr.Zero, 0x0003);

                            //TODO: I have to try removing the background of this cursor capture.
                            //Native.BitBlt(resultHdc, 0, 0, final.Width, final.Height, dcDesktop, (int)point.X + 3, (int)point.Y + 3, Native.CopyPixelOperation.SourceErase);

                            //Original, ignores the screen as background.
                            //Native.BitBlt(resultHdc, 0, 0, resultBitmap.Width, resultBitmap.Height, maskHdc, 0, resultBitmap.Height, Native.CopyPixelOperation.SourceCopy); //SourceCopy
                            //Native.BitBlt(resultHdc, 0, 0, resultBitmap.Width, resultBitmap.Height, maskHdc, 0, 0, Native.CopyPixelOperation.PatInvert); //SourceInvert

                            resultGraphics.ReleaseHdc(resultHdc);
                            ReleaseDC(hDesktop, dcDesktop);
                        }

                        DeleteObject(iconInfo.hbmMask);
                        DeleteDC(dcDesktop);

                        return(final);
                    }

                    DeleteObject(iconInfo.hbmColor);
                    DeleteObject(iconInfo.hbmMask);
                    DeleteObject(hicon);
                }

                var icon = Icon.FromHandle(hicon);
                return(icon.ToBitmap());
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Impossible to get the cursor.");
            }

            return(null);
        }
Example #60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XLinearGradientBrush"/> class.
 /// </summary>
 public XLinearGradientBrush(SysPoint point1, SysPoint point2, XColor color1, XColor color2)
     : this(new XPoint(point1), new XPoint(point2), color1, color2)
 {
 }