public Avalon(GeometryFactory Segments, Activation Attach, Activation Detach, ManipulationDeltaEventHandler Router,byte definition , bool Real = false) { if (!Real) { this.definition = definition; Data = Segments.Pattern(); ManipulationMode = Windows.UI.Xaml.Input.ManipulationModes.All; RenderTransform = new CompositeTransform(); RenderTransformOrigin = new Windows.Foundation.Point(0.5, 0.5); Fill = new SolidColorBrush(new Color { A = 0, R = 0, G = 0, B = 0 }); this.Attach = Attach; this.Detach = Detach; this.Router = Router; Tapped += Avalon_Tapped; Holding += Avalon_Holding; Loaded += Avalon_Loaded; Unloaded += Avalon_Unloaded; ManipulationDelta += Avalon_ManipulationDelta; this.Real = new Avalon(Segments, Attach, Detach, null, definition,true); this.Real.RenderTransform = RenderTransform; this.Real.RenderTransformOrigin = RenderTransformOrigin; this.Real.Data = Segments.Pattern(); this.Real.Fill = new SolidColorBrush(Colors.RosyBrown); Canvas.SetZIndex(this, 2); Canvas.SetZIndex(this.Real, 0); Avalon_Holding(null, null); } }
public DefaultEdgePointer() { RenderTransformOrigin = new Point(.5, .5); VerticalAlignment = VerticalAlignment.Center; HorizontalAlignment = HorizontalAlignment.Center; LayoutUpdated += EdgePointer_LayoutUpdated; }
void UpdateLocation() { var anchor = new Windows.Foundation.Point(0.65, 1); var location = new Geopoint(new BasicGeoposition { Latitude = _pin.Position.Latitude, Longitude = _pin.Position.Longitude }); MapControl.SetLocation(this, location); MapControl.SetNormalizedAnchorPoint(this, anchor); }
public Point GetMousePositionRelativeTo(IUserInputReceiver inputReceiver) { var receiver = (UIElement) inputReceiver; var position = receiver .TransformToVisual(Window.Current.Content) .TransformPoint(new FoundationPoint()); var finalPosition = new FoundationPoint( position.X + Window.Current.CoreWindow.PointerPosition.X, position.Y + Window.Current.CoreWindow.PointerPosition.Y ); return Mapper.Map<Point>(finalPosition); }
public static Point RotatePoint(Point pointToRotate, Point centerPoint, double angleInDegrees) { var angleInRadians = angleInDegrees * (Math.PI / 180); var cosTheta = Math.Cos(angleInRadians); var sinTheta = Math.Sin(angleInRadians); return new Point { X = (int) (cosTheta * (pointToRotate.X - centerPoint.X) - sinTheta * (pointToRotate.Y - centerPoint.Y) + centerPoint.X), Y = (int) (sinTheta * (pointToRotate.X - centerPoint.X) + cosTheta * (pointToRotate.Y - centerPoint.Y) + centerPoint.Y) }; }
/// <summary> /// Generate PathGeometry object with curved Path using supplied route points /// </summary> /// <param name="points">Route points</param> /// <param name="tension"></param> /// <param name="tolerance"></param> /// <returns></returns> public static PolyLineSegment GetCurveThroughPoints(Point[] points, Double tension, Double tolerance) { Debug.Assert(points != null); Debug.Assert(points.Length >= 2); Debug.Assert(tolerance > 0); var oPolyLineSegment = new PolyLineSegment(); if (points.Length == 2) { AddPointsToPolyLineSegment(oPolyLineSegment, points[0], points[0], points[1], points[1], tension, tolerance); } else { var iPoints = points.Length; for (var i = 0; i < iPoints; i++) { if (i == 0) { AddPointsToPolyLineSegment(oPolyLineSegment, points[0], points[0], points[1], points[2], tension, tolerance); } else if (i == iPoints - 2) { AddPointsToPolyLineSegment(oPolyLineSegment, points[i - 1], points[i], points[i + 1], points[i + 1], tension, tolerance); } else if (i != iPoints - 1) { AddPointsToPolyLineSegment(oPolyLineSegment, points[i - 1], points[i], points[i + 1], points[i + 2], tension, tolerance); } } oPolyLineSegment.Points.Insert(0, points[0]); } return oPolyLineSegment; }
public static void ClampCenterOfMass(object sender, FilterManipulationEventArgs args) { var inputProcessor = sender as InputProcessor; var target = inputProcessor.Target; var container = inputProcessor.Reference; var rect = target.RenderTransform.TransformBounds( new Windows.Foundation.Rect(0, 0, target.ActualWidth, target.ActualHeight)); var centerOfMass = new Windows.Foundation.Point { X = rect.Left + (rect.Width / 2), Y = rect.Top + (rect.Height / 2) }; var transform = new Windows.UI.Xaml.Media.CompositeTransform { CenterX = args.Pivot.X, CenterY = args.Pivot.Y, Rotation = args.Delta.Rotation, ScaleX = args.Delta.Scale, ScaleY = args.Delta.Scale, TranslateX = args.Delta.Translation.X, TranslateY = args.Delta.Translation.Y }; var transformedCenterOfMass = transform.TransformPoint(centerOfMass); if (transformedCenterOfMass.X < 0 || transformedCenterOfMass.X > container.ActualWidth || transformedCenterOfMass.Y < 0 || transformedCenterOfMass.Y > container.ActualHeight) { args.Delta = new Windows.UI.Input.ManipulationDelta { Rotation = 0F, Scale = 1F, Translation = new Windows.Foundation.Point(0, 0) }; } }
/// <summary> /// Implementation of <see cref="FilterManipulation"/> that forces at least <see cref="ManipulationFilter.TargetMinSize"/> /// pixels of the manipulation target to remain inside its container. /// This filter also makes sure the manipulation target does not become too small or too big. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> public static void Clamp(object sender, Manipulations.FilterManipulationEventArgs args) { var inputProcessor = sender as Manipulations.InputProcessor; var target = inputProcessor.Target; var container = inputProcessor.Reference; // Get the bounding box of the manipulation target, expressed in the coordinate system of its container var rect = target.RenderTransform.TransformBounds( new Windows.Foundation.Rect(0, 0, target.ActualWidth, target.ActualHeight)); // Make sure the manipulation target does not go completely outside the boundaries of its container var translate = new Windows.Foundation.Point { X = args.Delta.Translation.X, Y = args.Delta.Translation.Y }; if ((args.Delta.Translation.X > 0 && args.Delta.Translation.X > container.ActualWidth - rect.Left - ManipulationFilter.TargetMinInside) || (args.Delta.Translation.X < 0 && args.Delta.Translation.X < ManipulationFilter.TargetMinInside - rect.Right) || (args.Delta.Translation.Y > 0 && args.Delta.Translation.Y > container.ActualHeight - rect.Top - ManipulationFilter.TargetMinInside) || (args.Delta.Translation.Y < 0 && args.Delta.Translation.Y < ManipulationFilter.TargetMinInside - rect.Bottom)) { translate.X = 0; translate.Y = 0; } // Make sure the manipulation target does not become too small, or too big float scale = args.Delta.Scale < 1F ? (float)System.Math.Max(ManipulationFilter.TargetMinSize / System.Math.Min(rect.Width, rect.Height), args.Delta.Scale) : (float)System.Math.Min(ManipulationFilter.TargetMaxSize / System.Math.Max(rect.Width, rect.Height), args.Delta.Scale); args.Delta = new Windows.UI.Input.ManipulationDelta { Expansion = args.Delta.Expansion, Rotation = args.Delta.Rotation, Scale = scale, Translation = translate }; }
private void CropButton_Click(object sender, EventArgs e) { GeneralTransform transform = Crop.TransformToVisual(Image); var topLeftWindowsPoint = transform.Transform(new Point(0, 0)); topLeftWindowsPoint.X /= _scale; topLeftWindowsPoint.Y /= _scale; var bottomRightWindowsPoint = transform.Transform(new Point(Crop.Width, Crop.Height)); bottomRightWindowsPoint.X /= _scale; bottomRightWindowsPoint.Y /= _scale; var topLeftFoundationPoint = new Windows.Foundation.Point(Math.Round(topLeftWindowsPoint.X), Math.Round(topLeftWindowsPoint.Y)); var bottomRightFoundationPoint = new Windows.Foundation.Point(Math.Round(bottomRightWindowsPoint.X), Math.Round(bottomRightWindowsPoint.Y)); var reframingFilter = new ReframingFilter() { ReframingArea = new Windows.Foundation.Rect(topLeftFoundationPoint, bottomRightFoundationPoint) }; var filterEffect = new FilterEffect(_source) { Filters = new List<IFilter>() { reframingFilter } }; var renderer = new JpegRenderer(filterEffect) { OutputOption = OutputOption.PreserveAspectRatio, Quality = 1.0, Size = new Windows.Foundation.Size(bottomRightFoundationPoint.X - topLeftFoundationPoint.X, bottomRightFoundationPoint.Y - topLeftFoundationPoint.Y) }; IBuffer buffer = null; Task.Run(async () => { buffer = await renderer.RenderAsync(); }).Wait(); PhotoModel.Singleton.FromNewCrop(buffer.AsStream()); NavigationService.GoBack(); }
static UWPPoint AdjustToEndVertical(UWPPoint point, UWPSize itemSize, ScrollViewer scrollViewer) { var adjustment = scrollViewer.ViewportHeight - itemSize.Height; return(new UWPPoint(point.X, point.Y - adjustment)); }
private async Task DetectAndShowComputerVisionAnalysis() { this.progressIndicator.IsActive = true; this.imageControl.RenderTransform = null; foreach (var child in this.hostGrid.Children.Where(c => !(c is Image)).ToArray()) { this.hostGrid.Children.Remove(child); } if (this.DataContext is ImageAnalyzer img) { List <Task> tasks = new List <Task>(); if (img.AnalysisResult == null) { tasks.Add(img.AnalyzeImageAsync(new List <Details> { Details.Celebrities, Details.Landmarks })); } if (this.PerformOCRAnalysis && img.TextOperationResult == null) { tasks.Add(img.RecognizeTextAsync()); } if (this.PerformObjectDetection && img.DetectedObjects == null) { tasks.Add(img.DetectObjectsAsync()); } await Task.WhenAll(tasks); double renderedImageXTransform = this.imageControl.RenderSize.Width / this.bitmapImage.PixelWidth; double renderedImageYTransform = this.imageControl.RenderSize.Height / this.bitmapImage.PixelHeight; if (img.AnalysisResult.Faces != null) { foreach (FaceDescription face in img.AnalysisResult.Faces) { FaceIdentificationBorder faceUI = new FaceIdentificationBorder { Margin = new Thickness((face.FaceRectangle.Left * renderedImageXTransform) + ((this.ActualWidth - this.imageControl.RenderSize.Width) / 2), (face.FaceRectangle.Top * renderedImageYTransform) + ((this.ActualHeight - this.imageControl.RenderSize.Height) / 2), 0, 0), BalloonBackground = this.BalloonBackground, BalloonForeground = this.BalloonForeground }; faceUI.ShowFaceRectangle(face.FaceRectangle.Width * renderedImageXTransform, face.FaceRectangle.Height * renderedImageYTransform); var faceGender = Util.GetFaceGender(face.Gender); faceUI.ShowIdentificationData(face.Age, faceGender, 0, null); this.hostGrid.Children.Add(faceUI); this.GetCelebrityInfoIfAvailable(img, face.FaceRectangle, out string celebRecoName, out double celebRecoConfidence); if (!string.IsNullOrEmpty(celebRecoName)) { Border celebUI = new Border { Child = new TextBlock { Text = string.Format("{0} ({1}%)", celebRecoName, (uint)Math.Round(celebRecoConfidence * 100)), Foreground = this.BalloonForeground, FontSize = 14 }, Background = this.BalloonBackground, VerticalAlignment = VerticalAlignment.Top, HorizontalAlignment = HorizontalAlignment.Left }; celebUI.SizeChanged += (ev, ar) => { celebUI.Margin = new Thickness(faceUI.Margin.Left - (celebUI.ActualWidth - face.FaceRectangle.Width * renderedImageXTransform) / 2, faceUI.Margin.Top + 2 + face.FaceRectangle.Height * renderedImageYTransform, 0, 0); }; this.hostGrid.Children.Add(celebUI); } } } // Clean up any old results foreach (var child in this.hostGrid.Children.Where(c => (c is OCRBorder)).ToArray()) { this.hostGrid.Children.Remove(child); } // OCR request (Printed / Handwritten) if (this.PerformOCRAnalysis && img.TextOperationResult?.RecognitionResult?.Lines != null) { this.imageControl.RenderTransform = new RotateTransform { Angle = 0, CenterX = this.imageControl.RenderSize.Width / 2, CenterY = this.imageControl.RenderSize.Height / 2 }; foreach (Line line in img.TextOperationResult.RecognitionResult.Lines) { foreach (var word in line.Words) { double[] boundingBox = word?.BoundingBox?.ToArray() ?? new double[] { }; if (boundingBox.Length == 8) { double minLeft = renderedImageXTransform * (new List <double>() { boundingBox[0], boundingBox[2], boundingBox[4], boundingBox[6] }).Min(); double minTop = renderedImageYTransform * (new List <double>() { boundingBox[1], boundingBox[3], boundingBox[5], boundingBox[7] }).Min(); var points = new PointCollection() { new Windows.Foundation.Point(boundingBox[0] * renderedImageXTransform - minLeft, boundingBox[1] * renderedImageYTransform - minTop), new Windows.Foundation.Point(boundingBox[2] * renderedImageXTransform - minLeft, boundingBox[3] * renderedImageYTransform - minTop), new Windows.Foundation.Point(boundingBox[4] * renderedImageXTransform - minLeft, boundingBox[5] * renderedImageYTransform - minTop), new Windows.Foundation.Point(boundingBox[6] * renderedImageXTransform - minLeft, boundingBox[7] * renderedImageYTransform - minTop) }; // The four points (x-coordinate, y-coordinate) of the detected rectangle from the left-top corner and clockwise IEnumerable <Windows.Foundation.Point> leftPoints = points.OrderBy(p => p.X).Take(2); IEnumerable <Windows.Foundation.Point> rightPoints = points.OrderByDescending(p => p.X).Take(2); Windows.Foundation.Point leftTop = leftPoints.OrderBy(p => p.Y).FirstOrDefault(); Windows.Foundation.Point leftBottom = leftPoints.OrderByDescending(p => p.Y).FirstOrDefault(); Windows.Foundation.Point rightTop = rightPoints.OrderBy(p => p.Y).FirstOrDefault(); Windows.Foundation.Point rightBottom = rightPoints.OrderByDescending(p => p.Y).FirstOrDefault(); var orderedPoints = new PointCollection() { leftTop, rightTop, rightBottom, leftBottom }; // simple math to get angle of the text double diffWidth = Math.Abs(leftTop.X - rightTop.X); double diffHeight = Math.Abs(leftTop.Y - rightTop.Y); double sign = leftTop.Y > rightTop.Y ? -1 : 1; double angle = sign * Math.Atan2(diffHeight, diffWidth) * (180 / Math.PI); // angle in degrees OCRBorder ocrUI = new OCRBorder { Margin = new Thickness(minLeft + ((this.ActualWidth - this.imageControl.RenderSize.Width) / 2), minTop + ((this.ActualHeight - this.imageControl.RenderSize.Height) / 2), 0, 0) }; ocrUI.SetPoints(orderedPoints, word.Text, angle); this.hostGrid.Children.Add(ocrUI); } } } } if (this.PerformObjectDetection && img.DetectedObjects != null) { this.ShowObjectDetectionRegions(img.DetectedObjects); } } this.progressIndicator.IsActive = false; }
public static sides GetIntersectionData(Rect r, Point p) { return new sides() { Left = p.X < r.Left, Right = p.X > r.Right, Bottom = p.Y > r.Bottom, Top = p.Y < r.Top }; }
static UWPPoint AdjustToCenterVertical(UWPPoint point, UWPSize itemSize, ScrollViewer scrollViewer) { var adjustment = (scrollViewer.ViewportHeight / 2) - (itemSize.Height / 2); return(new UWPPoint(point.X, point.Y - adjustment)); }
public static Point GetEdgeEndpointOnTriangle(Point oVertexLocation, double mDHalfWidth, Point otherEndpoint) { // Instead of doing geometry calculations similar to what is done in // VertexDrawingHistory.GetEdgePointOnRectangle(), make use of that // method by making the triangle look like a rectangle. First, figure // out how to rotate the triangle about the vertex location so that the // side containing the endpoint is vertical and to the right of the // vertex location. var dEdgeAngle = MathHelper.GetAngleBetweenPointsRadians( oVertexLocation, otherEndpoint); var dEdgeAngleDegrees = MathHelper.RadiansToDegrees(dEdgeAngle); double dAngleToRotateDegrees; if (dEdgeAngleDegrees >= -30.0 && dEdgeAngleDegrees < 90.0) { dAngleToRotateDegrees = 30.0; } else if (dEdgeAngleDegrees >= -150.0 && dEdgeAngleDegrees < -30.0) { dAngleToRotateDegrees = 270.0; } else { dAngleToRotateDegrees = 150.0; } // Now create a rotated rectangle that is centered on the vertex // location and that has the vertical, endpoint-containing triangle // side as the rectangle's right edge. var dWidth = 2.0 * mDHalfWidth; var oRotatedRectangle = new Rect( oVertexLocation.X, oVertexLocation.Y - mDHalfWidth, dWidth * MathHelper.Tangent30Degrees, dWidth ); var oMatrix = GetRotatedMatrix(oVertexLocation, dAngleToRotateDegrees); // Rotate the other vertex location. var oRotatedOtherVertexLocation = oMatrix.Transform(otherEndpoint); // GetEdgeEndpointOnRectangle will compute an endpoint on the // rectangle's right edge. var oRotatedEdgeEndpoint = GetEdgeEndpointOnRectangle(oVertexLocation, oRotatedRectangle, oRotatedOtherVertexLocation); // Now rotate the edge endpoint in the other direction. oMatrix = GetRotatedMatrix(oVertexLocation, -dAngleToRotateDegrees); return(oMatrix.Transform(oRotatedEdgeEndpoint)); }
private Point UpdateTargetEpData(Point from, Point to) { var dir = MathHelper.GetDirection(from, to); return(_edgePointerForTarget.Update(from, dir, _edgePointerForTarget.NeedRotation ? (-MathHelper.GetAngleBetweenPoints(from, to).ToDegrees()) : 0)); }
public static double GetDistanceBetweenPoints(Point point1, Point point2) { return Math.Sqrt(Math.Pow(point2.X - point1.X, 2) + Math.Pow(point2.Y - point1.Y, 2)); }
/// <summary> /// Changes the current camera effect. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void OnMyCameraMediaElementTapped(object sender, GestureEventArgs e) { var uiTapPoint = e.GetPosition(_mediaElement); if (_focusSemaphore.WaitOne(0)) { // Get tap coordinates as a foundation point var tapPoint = new Windows.Foundation.Point(uiTapPoint.X, uiTapPoint.Y); // adjust to center focus on the tap point var displayOrigin = new Windows.Foundation.Point( tapPoint.X - _focusRegionSize.Width / 2, tapPoint.Y - _focusRegionSize.Height / 2); // adjust for resolution difference between preview image and the canvas var viewFinderOrigin = new Windows.Foundation.Point(displayOrigin.X , displayOrigin.Y); var focusrect = new Windows.Foundation.Rect(viewFinderOrigin, _focusRegionSize); // clip to preview resolution var viewPortRect = new Windows.Foundation.Rect(0, 0,_camera.PreviewResolution.Width,_camera.PreviewResolution.Height); focusrect.Intersect(viewPortRect); _camera.FocusRegion = focusrect; // show a focus indicator FocusIndicator.Margin = new Thickness(uiTapPoint.X - (_focusRegionSize.Width/2), uiTapPoint.Y - (_focusRegionSize.Height/2), 0, 0); FocusIndicator.SetValue(Shape.StrokeProperty, _notFocusedBrush); FocusIndicator.SetValue(Canvas.VisibilityProperty, Visibility.Visible); CameraFocusStatus status = await _camera.FocusAsync(); if (status == CameraFocusStatus.Locked) { FocusIndicator.SetValue(Shape.StrokeProperty, _focusedBrush); _manuallyFocused = true; _camera.SetProperty(KnownCameraPhotoProperties.LockedAutoFocusParameters, AutoFocusParameters.Exposure & AutoFocusParameters.Focus & AutoFocusParameters.WhiteBalance); } else { _manuallyFocused = false; _camera.SetProperty(KnownCameraPhotoProperties.LockedAutoFocusParameters, AutoFocusParameters.None); } _focusSemaphore.Release(); } }
public static Vector GetDirection(Point from, Point to) { var dir = new Vector(from.X - to.X, from.Y - to.Y); dir.Normalize(); return dir; }
public static double GetAngleBetweenPoints(Point point1, Point point2) { return Math.Atan2(point1.Y - point2.Y, point2.X - point1.X); }
public static Double GetAngleBetweenPointsRadians(Point point1, Point point2) { return (Math.Atan2(point1.Y - point2.Y, point2.X - point1.X)); }
public static Point GetCloserPoint(Point start, Point a, Point b) { var r1 = GetDistance(start, a); var r2 = GetDistance(start, b); return r1 < r2 ? a : b; }
public static double GetDistance(Point a, Point b) { return ((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y)); }
/// <summary> /// Starts spinning. /// </summary> /// <param name="speed">The speed.</param> /// <param name="position">The position.</param> /// <param name="aroundPoint">The point to spin around.</param> public void StartSpin(Vector2 speed, Point position, Vector3 aroundPoint) { CameraController.StartSpin(speed, position, aroundPoint); }
public static bool IsIntersected(Rect r, Point a, Point b) { // var start = new Point(a.X, a.Y); /* line endpoints */ var codeA = GetIntersectionData(r, a); var codeB = GetIntersectionData(r, b); if (codeA.IsInside() && codeB.IsInside()) return true; /* while one of the endpoints are outside of rectangle */ while (!codeA.IsInside() || !codeB.IsInside()) { /* if both points are at one rectangle side then line do not cross the rectangle */ if (codeA.SameSide(codeB)) return false; /* select point with zero code */ sides code; Point c; /* one of the points */ if (!codeA.IsInside()) { code = codeA; c = a; } else { code = codeB; c = b; } /* if c is on the left of r then move c on the line x = r->x_min if c is on the right side of r then move c on the line x = r->x_max */ if (code.Left) { c.Y += (a.Y - b.Y) * (r.Left - c.X) / (a.X - b.X); c.X = r.Left; } else if (code.Right) { c.Y += (a.Y - b.Y) * (r.Right - c.X) / (a.X - b.X); c.X = r.Right; }/* if c is below r then move c on the line y = r->y_min if c above the r then move c on the line y = r->y_max */ else if (code.Bottom) { c.X += (a.X - b.X) * (r.Bottom - c.Y) / (a.Y - b.Y); c.Y = r.Bottom; } else if (code.Top) { c.X += (a.X - b.X) * (r.Top - c.Y) / (a.Y - b.Y); c.Y = r.Top; } /* refresh code */ if (code == codeA) { a = c; codeA = GetIntersectionData(r, a); } else { b = c; codeB = GetIntersectionData(r, b); } } return true; }
public static Point GetEdgeEndpointOnCircle(Point oVertexALocation, double dVertexARadius, Point oVertexBLocation) { Debug.Assert(dVertexARadius >= 0); var dEdgeAngle = MathHelper.GetAngleBetweenPointsRadians(oVertexALocation, oVertexBLocation); return(new Point( oVertexALocation.X + (dVertexARadius * Math.Cos(dEdgeAngle)), oVertexALocation.Y - (dVertexARadius * Math.Sin(dEdgeAngle)) )); }
private void InitializeCamera() { var captureResolutions = PhotoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).ToArray(); var previewResolutions = PhotoCaptureDevice.GetAvailablePreviewResolutions(CameraSensorLocation.Back).ToArray(); Windows.Foundation.Size captureResolution = new Windows.Foundation.Size(640, 480); Windows.Foundation.Size previewResolution = new Windows.Foundation.Size(640, 480); try { captureResolution = GetFirstWideResolution(captureResolutions); previewResolution = GetFirstWideResolution(previewResolutions); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Unable to get wide resolution for viewfinder, using 640x480"); } var task = PhotoCaptureDevice.OpenAsync(CameraSensorLocation.Back, captureResolution).AsTask(); task.Wait(); _device = task.Result; _device.SetPreviewResolutionAsync(previewResolution).AsTask().Wait(); var objectResolutionSide = _device.PreviewResolution.Height * (ReaderBorder.Height - 2 * ReaderBorder.Margin.Top) / 480; var objectResolution = new Windows.Foundation.Size(objectResolutionSide, objectResolutionSide); var focusRegionSize = new Windows.Foundation.Size(objectResolutionSide, objectResolutionSide); var objectSize = OpticalReaderLib.OpticalReaderTask.Instance.ObjectSize; if (objectSize.Width * objectSize.Height > 0) { var parameters = OpticalReaderLib.Utilities.GetSuggestedParameters(_device.PreviewResolution, _device.SensorRotationInDegrees, objectSize, objectResolution); _zoom = Math.Max(parameters.Zoom, 1.0); } else { _zoom = 1.0; } var centerPoint = new Windows.Foundation.Point(previewResolution.Width / 2, previewResolution.Height / 2); _device.FocusRegion = new Windows.Foundation.Rect( centerPoint.X - focusRegionSize.Width / 2, centerPoint.Y - focusRegionSize.Height / 2, focusRegionSize.Width, focusRegionSize.Height); ViewfinderVideoBrush.SetSource(_device); }
public static Point GetEdgeEndpointOnRectangle(Point oVertexALocation, Rect oVertexARectangle, Point oVertexBLocation) { /* if (oVertexALocation == oVertexBLocation) * return oVertexALocation; * * Double dVertexAX = oVertexALocation.X; * Double dVertexAY = oVertexALocation.Y; * * Double dVertexBX = oVertexBLocation.X; * Double dVertexBY = oVertexBLocation.Y; * * Double dHalfVertexARectangleWidth = oVertexARectangle.Width / 2.0; * Double dHalfVertexARectangleHeight = oVertexARectangle.Height / 2.0; * * // Get the angle between vertex A and vertex B. * * Double dEdgeAngle = MathHelper.GetAngleBetweenPointsRadians( * oVertexALocation, oVertexBLocation); * * // Get the angle that defines the aspect ratio of vertex A's rectangle. * * Double dAspectAngle = Math.Atan2( * dHalfVertexARectangleHeight, dHalfVertexARectangleWidth); * * if (dEdgeAngle >= -dAspectAngle && dEdgeAngle < dAspectAngle) * { * // For a square, this is -45 degrees to 45 degrees. * Debug.Assert(dVertexBX != dVertexAX); * return new Point( * dVertexAX + dHalfVertexARectangleWidth, * dVertexAY + dHalfVertexARectangleWidth * * ((dVertexBY - dVertexAY) / (dVertexBX - dVertexAX)) * ); * } * * if (dEdgeAngle >= dAspectAngle && dEdgeAngle < Math.PI - dAspectAngle) * { * // For a square, this is 45 degrees to 135 degrees. * //Debug.Assert(dVertexBY != dVertexAY); * return new Point( * dVertexAX + dHalfVertexARectangleHeight * * ((dVertexBX - dVertexAX) / (dVertexAY - dVertexBY)), * dVertexAY - dHalfVertexARectangleHeight * ); * } * * if (dEdgeAngle < -dAspectAngle && dEdgeAngle >= -Math.PI + dAspectAngle) * { * // For a square, this is -45 degrees to -135 degrees. * Debug.Assert(dVertexBY != dVertexAY); * return new Point( * dVertexAX + dHalfVertexARectangleHeight * * ((dVertexBX - dVertexAX) / (dVertexBY - dVertexAY)), * dVertexAY + dHalfVertexARectangleHeight * ); * } * * // For a square, this is 135 degrees to 180 degrees and -135 degrees to * // -180 degrees. * Debug.Assert(dVertexAX != dVertexBX); * return new Point( * dVertexAX - dHalfVertexARectangleWidth, * dVertexAY + dHalfVertexARectangleWidth * * ((dVertexBY - dVertexAY) / (dVertexAX - dVertexBX)) * );*/ var leftSide = Intersects(new Vector(oVertexALocation.X, oVertexALocation.Y), new Vector(oVertexBLocation.X, oVertexBLocation.Y), new Vector(oVertexARectangle.X, oVertexARectangle.Y), new Vector(oVertexARectangle.X, oVertexARectangle.Y + oVertexARectangle.Height)); var bottomSide = Intersects(new Vector(oVertexALocation.X, oVertexALocation.Y), new Vector(oVertexBLocation.X, oVertexBLocation.Y), new Vector(oVertexARectangle.X, oVertexARectangle.Y + oVertexARectangle.Height), new Vector(oVertexARectangle.X + oVertexARectangle.Width, oVertexARectangle.Y + oVertexARectangle.Height)); var rightSide = Intersects(new Vector(oVertexALocation.X, oVertexALocation.Y), new Vector(oVertexBLocation.X, oVertexBLocation.Y), new Vector(oVertexARectangle.X + oVertexARectangle.Width, oVertexARectangle.Y), new Vector(oVertexARectangle.X + oVertexARectangle.Width, oVertexARectangle.Y + oVertexARectangle.Height)); var topSide = Intersects(new Vector(oVertexALocation.X, oVertexALocation.Y), new Vector(oVertexBLocation.X, oVertexBLocation.Y), new Vector(oVertexARectangle.X, oVertexARectangle.Y), new Vector(oVertexARectangle.X + oVertexARectangle.Width, oVertexARectangle.Y)); var pt = new Point(oVertexALocation.X, oVertexALocation.Y); // Get the rectangle side where intersection of the proposed Edge path occurred. if (leftSide != null) { pt = new Point(leftSide.Value.X, leftSide.Value.Y); } else if (bottomSide != null) { pt = new Point(bottomSide.Value.X, bottomSide.Value.Y); } else if (rightSide != null) { pt = new Point(rightSide.Value.X, rightSide.Value.Y); } else if (topSide != null) { pt = new Point(topSide.Value.X, topSide.Value.Y); } return(pt); }
private async Task<Tuple<ProcessResult, WriteableBitmap>> ProcessFrameAsync(OpticalReaderLib.Frame frame) { //System.Diagnostics.Debug.WriteLine("Start processing"); var rectSize = new Windows.Foundation.Size( ReaderBorder.ActualWidth / Canvas.ActualWidth * frame.Dimensions.Width / _zoom, ReaderBorder.ActualHeight / Canvas.ActualHeight * frame.Dimensions.Height / _zoom); var rectOrigin = new Windows.Foundation.Point( frame.Dimensions.Width / 2 - rectSize.Width / 2, frame.Dimensions.Height / 2 - rectSize.Height / 2); var area = new Windows.Foundation.Rect(rectOrigin, rectSize); ProcessResult result = null; try { result = await OpticalReaderTask.Instance.Processor.ProcessAsync(frame, area, _rotation); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(String.Format("Processing frame failed: {0}\n{1}", ex.Message, ex.StackTrace)); } //System.Diagnostics.Debug.WriteLine("Stop processing"); InterestAreaPolygon.Points = null; if (result != null) { _lastSuccess = DateTime.Now; var thumbnail = GenerateThumbnail(); var interestPointCollection = new PointCollection(); foreach (var point in result.InterestPoints) { interestPointCollection.Add(new System.Windows.Point(point.X, point.Y)); } InterestAreaPolygon.Points = interestPointCollection; return new Tuple<ProcessResult, WriteableBitmap>(result, thumbnail); } else { var sinceLastSuccess = DateTime.Now - _lastSuccess; if (sinceLastSuccess > OpticalReaderTask.Instance.FocusInterval) { try { var status = await _device.FocusAsync(); _lastSuccess = DateTime.Now; // todo use camera focus lock status } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(String.Format("Focusing camera failed: {0}\n{1}", ex.Message, ex.StackTrace)); } } return null; } }
/// <summary> /// Create and apply edge path using calculated ER parameters stored in edge /// </summary> /// <param name="useCurrentCoords">Use current vertices coordinates or final coorfinates (for.ex if move animation is active final coords will be its destination)</param> /// <param name="externalRoutingPoints">Provided custom routing points will be used instead of stored ones.</param> /// <param name="updateLabel">Should edge label be updated in this pass</param> public virtual void PrepareEdgePath(bool useCurrentCoords = false, Measure.Point[] externalRoutingPoints = null, bool updateLabel = true) { //do not calculate invisible edges if ((Visibility != Visibility.Visible && !IsHiddenEdgesUpdated) && Source == null || Target == null || ManualDrawing || !IsTemplateLoaded) { return; } #region Get the inputs //get the size of the source var sourceSize = new Size { Width = Source.ActualWidth, Height = Source.ActualHeight }; if (CustomHelper.IsInDesignMode(this)) { sourceSize = new Size(80, 20); } //get the position center of the source var sourcePos = new Point { X = (useCurrentCoords ? GraphAreaBase.GetX(Source) : GraphAreaBase.GetFinalX(Source)) + sourceSize.Width * .5, Y = (useCurrentCoords ? GraphAreaBase.GetY(Source) : GraphAreaBase.GetFinalY(Source)) + sourceSize.Height * .5 }; //get the size of the target var targetSize = new Size { Width = Target.ActualWidth, Height = Target.ActualHeight }; if (CustomHelper.IsInDesignMode(this)) { targetSize = new Size(80, 20); } //get the position center of the target var targetPos = new Point { X = (useCurrentCoords ? GraphAreaBase.GetX(Target) : GraphAreaBase.GetFinalX(Target)) + targetSize.Width * .5, Y = (useCurrentCoords ? GraphAreaBase.GetY(Target) : GraphAreaBase.GetFinalY(Target)) + targetSize.Height * .5 }; var routedEdge = Edge as IRoutingInfo; if (routedEdge == null) { throw new GX_InvalidDataException("Edge must implement IRoutingInfo interface"); } //get the route informations var routeInformation = externalRoutingPoints ?? routedEdge.RoutingPoints; // Get the TopLeft position of the Source Vertex. var sourcePos1 = new Point { X = (useCurrentCoords ? GraphAreaBase.GetX(Source) : GraphAreaBase.GetFinalX(Source)), Y = (useCurrentCoords ? GraphAreaBase.GetY(Source) : GraphAreaBase.GetFinalY(Source)) }; // Get the TopLeft position of the Target Vertex. var targetPos1 = new Point { X = (useCurrentCoords ? GraphAreaBase.GetX(Target) : GraphAreaBase.GetFinalX(Target)), Y = (useCurrentCoords ? GraphAreaBase.GetY(Target) : GraphAreaBase.GetFinalY(Target)) }; var hasEpSource = _edgePointerForSource != null; var hasEpTarget = _edgePointerForTarget != null; #endregion //if self looped edge if (IsSelfLooped) { PrepareSelfLoopedEdge(sourcePos1); return; } //check if we have some edge route data var hasRouteInfo = routeInformation != null && routeInformation.Length > 1; //calculate source and target edge attach points if (RootArea != null && !hasRouteInfo && RootArea.EnableParallelEdges && ParallelEdgeOffset != 0) { sourcePos = GetParallelOffset(Source, Target, ParallelEdgeOffset); targetPos = GetParallelOffset(Target, Source, -ParallelEdgeOffset); } /* Rectangular shapes implementation by bleibold */ var gEdge = Edge as IGraphXCommonEdge; Point p1; Point p2; //calculate edge source (p1) and target (p2) endpoints based on different settings if (gEdge != null && gEdge.SourceConnectionPointId.HasValue) { var sourceCp = Source.GetConnectionPointById(gEdge.SourceConnectionPointId.Value, true); if (sourceCp == null) { throw new GX_ObjectNotFoundException(string.Format("Can't find source vertex VCP by edge source connection point Id({1}) : {0}", Source, gEdge.SourceConnectionPointId)); } if (sourceCp.Shape == VertexShape.None) { p1 = sourceCp.RectangularSize.Center(); } else { var targetCpPos = gEdge.TargetConnectionPointId.HasValue ? Target.GetConnectionPointById(gEdge.TargetConnectionPointId.Value, true).RectangularSize.Center() : (hasRouteInfo ? routeInformation[1].ToWindows() : (targetPos)); p1 = GeometryHelper.GetEdgeEndpoint(sourceCp.RectangularSize.Center(), sourceCp.RectangularSize, targetCpPos, sourceCp.Shape); } } else { p1 = GeometryHelper.GetEdgeEndpoint(sourcePos, new SysRect(sourcePos1, sourceSize), (hasRouteInfo ? routeInformation[1].ToWindows() : (targetPos)), Source.VertexShape); } if (gEdge != null && gEdge.TargetConnectionPointId.HasValue) { var targetCp = Target.GetConnectionPointById(gEdge.TargetConnectionPointId.Value, true); if (targetCp == null) { throw new GX_ObjectNotFoundException(string.Format("Can't find target vertex VCP by edge target connection point Id({1}) : {0}", Target, gEdge.TargetConnectionPointId)); } if (targetCp.Shape == VertexShape.None) { p2 = targetCp.RectangularSize.Center(); } else { var sourceCpPos = gEdge.SourceConnectionPointId.HasValue ? Source.GetConnectionPointById(gEdge.SourceConnectionPointId.Value, true).RectangularSize.Center() : hasRouteInfo ? routeInformation[routeInformation.Length - 2].ToWindows() : (sourcePos); p2 = GeometryHelper.GetEdgeEndpoint(targetCp.RectangularSize.Center(), targetCp.RectangularSize, sourceCpPos, targetCp.Shape); } } else { p2 = GeometryHelper.GetEdgeEndpoint(targetPos, new SysRect(targetPos1, targetSize), hasRouteInfo ? routeInformation[routeInformation.Length - 2].ToWindows() : (sourcePos), Target.VertexShape); } SourceConnectionPoint = p1; TargetConnectionPoint = p2; _linegeometry = new PathGeometry(); PathFigure lineFigure; //if we have route and route consist of 2 or more points if (RootArea != null && hasRouteInfo) { //replace start and end points with accurate ones var routePoints = routeInformation.ToWindows().ToList(); routePoints.Remove(routePoints.First()); routePoints.Remove(routePoints.Last()); routePoints.Insert(0, p1); routePoints.Add(p2); if (RootArea.EdgeCurvingEnabled) { var oPolyLineSegment = GeometryHelper.GetCurveThroughPoints(routePoints.ToArray(), 0.5, RootArea.EdgeCurvingTolerance); if (hasEpTarget) { UpdateTargetEpData(oPolyLineSegment.Points[oPolyLineSegment.Points.Count - 1], oPolyLineSegment.Points[oPolyLineSegment.Points.Count - 2]); oPolyLineSegment.Points.RemoveAt(oPolyLineSegment.Points.Count - 1); } if (hasEpSource) { UpdateSourceEpData(oPolyLineSegment.Points.First(), oPolyLineSegment.Points[1]); } lineFigure = GeometryHelper.GetPathFigureFromPathSegments(routePoints[0], true, true, oPolyLineSegment); #if WPF //freeze and create resulting geometry GeometryHelper.TryFreeze(oPolyLineSegment); #endif } else { if (hasEpSource) { UpdateSourceEpData(routePoints.First(), routePoints[1]); } if (hasEpTarget) { routePoints[routePoints.Count - 1] = routePoints[routePoints.Count - 1].Subtract(UpdateTargetEpData(p2, routePoints[routePoints.Count - 2])); } var pcol = new PointCollection(); foreach (var item in routePoints) { pcol.Add(item); } lineFigure = new PathFigure { StartPoint = p1, Segments = new PathSegmentCollection { new PolyLineSegment { Points = pcol } }, IsClosed = false }; } } else // no route defined { if (hasEpSource) { UpdateSourceEpData(p1, p2); } if (hasEpTarget) { p2 = p2.Subtract(UpdateTargetEpData(p2, p1)); } lineFigure = new PathFigure { StartPoint = p1, Segments = new PathSegmentCollection { new LineSegment() { Point = p2 } }, IsClosed = false }; } ((PathGeometry)_linegeometry).Figures.Add(lineFigure); #if WPF GeometryHelper.TryFreeze(lineFigure); GeometryHelper.TryFreeze(_linegeometry); #endif if (ShowLabel && _edgeLabelControl != null && _updateLabelPosition && updateLabel) { _edgeLabelControl.UpdatePosition(); } }
public static bool AreVirtuallyEqual(Point p1, Point p2) { return(AreVirtuallyEqual(p1.X, p2.X) && AreVirtuallyEqual(p1.Y, p2.Y)); }
static UWPPoint AdjustToCenterHorizontal(UWPPoint point, UWPSize itemSize, ScrollViewer scrollViewer) { var adjustment = (scrollViewer.ViewportWidth / 2) - (itemSize.Width / 2); return(new UWPPoint(point.X - adjustment, point.Y)); }
public void DrawLine(float sx, float sy, float ex, float ey, float w) { if (polyline != null) { var n = polylinePoints.Count; if (polylineLength == 0) { var sp = new Point(sx, sy); if (n == 0) { polylinePoints.Add(sp); n++; } else { polylinePoints[0] = sp; } polylineLength = 1; } var ep = new Point(ex, ey); if (polylineLength >= n) { polylinePoints.Add(ep); } else { polylinePoints[polylineLength] = ep; } polylineLength++; var s = polylineShape; if (s.Color != _currentColor) { s.Color = _currentColor; polyline.Stroke = _currentColor.GetBrush(); } if (s.Thickness != w) { s.Thickness = w; polyline.StrokeThickness = w; } } else { var s = GetNextShape(TypeId.Line); var line = (Line)s.Element; if (s.X != sx) { s.X = sx; line.X1 = sx; } if (s.Y != sy) { s.Y = sy; line.Y1 = sy; } if (s.Width != ex) { s.Width = ex; line.X2 = ex; } if (s.Height != ey) { s.Height = ey; line.Y2 = ey; } if (s.Color != _currentColor) { s.Color = _currentColor; line.Stroke = _currentColor.GetBrush(); } if (s.Thickness != w) { s.Thickness = w; line.StrokeThickness = w; } } }
static UWPPoint AdjustToEndHorizontal(UWPPoint point, UWPSize itemSize, ScrollViewer scrollViewer) { var adjustment = scrollViewer.ViewportWidth - itemSize.Width; return(new UWPPoint(point.X - adjustment, point.Y)); }
public static PointF ToPointF(this Point pt) { return(new PointF((float)pt.X, (float)pt.Y)); }
private async void VideoCanvasOnTap(object sender, GestureEventArgs e) { try { System.Windows.Point uiTapPoint = e.GetPosition(VideoCanvas); if (PhotoCaptureDevice.IsFocusRegionSupported(PhotoCaptureDevice.SensorLocation) && _focusSemaphore.WaitOne(0)) { // Get tap coordinates as a foundation point var tapPoint = new Windows.Foundation.Point(uiTapPoint.X, uiTapPoint.Y); double xRatio = VideoCanvas.ActualHeight / PhotoCaptureDevice.PreviewResolution.Width; double yRatio = VideoCanvas.ActualWidth / PhotoCaptureDevice.PreviewResolution.Height; // adjust to center focus on the tap point var displayOrigin = new Windows.Foundation.Point( tapPoint.Y - _focusRegionSize.Width / 2, (VideoCanvas.ActualWidth - tapPoint.X) - _focusRegionSize.Height / 2); // adjust for resolution difference between preview image and the canvas var viewFinderOrigin = new Windows.Foundation.Point(displayOrigin.X / xRatio, displayOrigin.Y / yRatio); var focusrect = new Windows.Foundation.Rect(viewFinderOrigin, _focusRegionSize); // clip to preview resolution var viewPortRect = new Windows.Foundation.Rect(0, 0, PhotoCaptureDevice.PreviewResolution.Width, PhotoCaptureDevice.PreviewResolution.Height); focusrect.Intersect(viewPortRect); PhotoCaptureDevice.FocusRegion = focusrect; // show a focus indicator FocusIndicator.SetValue(Shape.StrokeProperty, _notFocusedBrush); FocusIndicator.SetValue(Canvas.LeftProperty, uiTapPoint.X - _focusRegionSize.Width / 2); FocusIndicator.SetValue(Canvas.TopProperty, uiTapPoint.Y - _focusRegionSize.Height / 2); FocusIndicator.SetValue(VisibilityProperty, Visibility.Visible); CameraFocusStatus status = await PhotoCaptureDevice.FocusAsync(); if (status == CameraFocusStatus.Locked) { FocusIndicator.SetValue(Shape.StrokeProperty, _focusedBrush); _manuallyFocused = true; PhotoCaptureDevice.SetProperty(KnownCameraPhotoProperties.LockedAutoFocusParameters, AutoFocusParameters.Exposure & AutoFocusParameters.Focus & AutoFocusParameters.WhiteBalance); } else { _manuallyFocused = false; PhotoCaptureDevice.SetProperty(KnownCameraPhotoProperties.LockedAutoFocusParameters, AutoFocusParameters.None); } _focusSemaphore.Release(); } await Capture(); } catch (Exception exception) { Deployment.Current.Dispatcher.BeginInvoke(() => { new CustomMessageDialog( AppMessages.CaptureVideoFailed_Title, String.Format(AppMessages.CaptureVideoFailed, exception.Message), App.AppInformation, MessageDialogButtons.Ok).ShowDialog(); }); } }
/// <summary> /// Occurs when the manipulation is completed. /// </summary> /// <param name="e">The <see cref="ManipulationEventArgs"/> instance containing the event data.</param> public override void Completed(Point e) { base.Completed(e); }
public static bool IsCloseTo(this Windows.Foundation.Point point1, Windows.Foundation.Point point2) { return(default(bool)); }
private void _joyStick_JoyStickUpdated(object sender, Windows.Foundation.Point e) { JoystickDisplayX = e.X * 100; JoystickDisplayY = (-e.Y * 100); }
public void SetManualPosition(Point position) { LastKnownRectSize = new Rect(new Point(position.X - DesiredSize.Width * .5, position.Y - DesiredSize.Height * .5), DesiredSize); Arrange(LastKnownRectSize); }
public static Windows.Foundation.Point LogicalToPhysicalPixels(this Windows.Foundation.Point point) { return(point); }
private static void AddPointsToPolyLineSegment(PolyLineSegment oPolyLineSegment, Point oPoint0, Point oPoint1, Point oPoint2, Point oPoint3, double dTension, double dTolerance) { Debug.Assert(oPolyLineSegment != null); Debug.Assert(dTolerance > 0); var iPoints = (int)((Math.Abs(oPoint1.X - oPoint2.X) + Math.Abs(oPoint1.Y - oPoint2.Y)) / dTolerance); var oPolyLineSegmentPoints = oPolyLineSegment.Points; if (iPoints <= 2) { oPolyLineSegmentPoints.Add(oPoint2); } else { var dSx1 = dTension * (oPoint2.X - oPoint0.X); var dSy1 = dTension * (oPoint2.Y - oPoint0.Y); var dSx2 = dTension * (oPoint3.X - oPoint1.X); var dSy2 = dTension * (oPoint3.Y - oPoint1.Y); var dAx = dSx1 + dSx2 + 2 * oPoint1.X - 2 * oPoint2.X; var dAy = dSy1 + dSy2 + 2 * oPoint1.Y - 2 * oPoint2.Y; var dBx = -2 * dSx1 - dSx2 - 3 * oPoint1.X + 3 * oPoint2.X; var dBy = -2 * dSy1 - dSy2 - 3 * oPoint1.Y + 3 * oPoint2.Y; var dCx = dSx1; var dCy = dSy1; var dDx = oPoint1.X; var dDy = oPoint1.Y; // Note that this starts at 1, not 0. for (var i = 1; i < iPoints; i++) { var t = (double)i / (iPoints - 1); var oPoint = new Point( dAx * t * t * t + dBx * t * t + dCx * t + dDx, dAy * t * t * t + dBy * t * t + dCy * t + dDy ); oPolyLineSegmentPoints.Add(oPoint); } } }
private void DisplayContextualMenu(Windows.Foundation.Point globalPos) { var part = _editor.Part; if (_editor.Part == null) { return; } using (var rootBlock = _editor.GetRootBlock()) { var contentBlock = _lastSelectedBlock; if (contentBlock == null) { return; } var isRoot = contentBlock.Id == rootBlock.Id; if (!isRoot && (contentBlock.Type == "Container")) { return; } var onRawContent = part.Type == "Raw Content"; var onTextDocument = part.Type == "Text Document"; var isEmpty = _editor.IsEmpty(contentBlock); var supportedTypes = _editor.SupportedAddBlockTypes; var supportedExports = _editor.GetSupportedExportMimeTypes(onRawContent ? rootBlock : contentBlock); var supportedImports = _editor.GetSupportedImportMimeTypes(contentBlock); var supportedStates = _editor.GetSupportedTargetConversionStates(contentBlock); var hasTypes = (supportedTypes != null) && supportedTypes.Any(); var hasExports = (supportedExports != null) && supportedExports.Any(); var hasImports = (supportedImports != null) && supportedImports.Any(); var hasStates = (supportedStates != null) && supportedStates.Any(); var displayConvert = hasStates && !isEmpty; var displayAddBlock = hasTypes && isRoot; var displayAddImage = false; // hasTypes && isRoot; var displayRemove = !isRoot; var displayCopy = (onTextDocument ? !isRoot : !onRawContent); var displayPaste = hasTypes && isRoot; var displayImport = hasImports; var displayExport = hasExports; var displayClipboard = hasExports && supportedExports.Contains(MimeType.OFFICE_CLIPBOARD); var flyoutMenu = new MenuFlyout(); if (displayAddBlock || displayAddImage) { var flyoutSubItem = new MenuFlyoutSubItem { Text = "Add..." }; flyoutMenu.Items.Add(flyoutSubItem); if (displayAddBlock) { for (var i = 0; i < supportedTypes.Count(); ++i) { var command = new FlyoutCommand(supportedTypes[i], (cmd) => { Popup_CommandHandler_AddBlock(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Add " + supportedTypes[i], Command = command }; flyoutSubItem.Items.Add(flyoutItem); } } if (displayAddImage) { var command = new FlyoutCommand("Image", (cmd) => { Popup_CommandHandler_AddImage(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Add Image", Command = command }; flyoutSubItem.Items.Add(flyoutItem); } } if (displayRemove) { var command = new FlyoutCommand("Remove", (cmd) => { Popup_CommandHandler_Remove(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Remove", Command = command }; flyoutMenu.Items.Add(flyoutItem); } if (displayConvert) { var command = new FlyoutCommand("Convert", (cmd) => { Popup_CommandHandler_Convert(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Convert", Command = command }; flyoutMenu.Items.Add(flyoutItem); } if (displayCopy || displayClipboard || displayPaste) { var flyoutSubItem = new MenuFlyoutSubItem { Text = "Copy/Paste..." }; flyoutMenu.Items.Add(flyoutSubItem); //if (displayCopy) { var command = new FlyoutCommand("Copy", (cmd) => { Popup_CommandHandler_Copy(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Copy", Command = command, IsEnabled = displayCopy }; flyoutSubItem.Items.Add(flyoutItem); } //if (displayClipboard) { var command = new FlyoutCommand("Copy To Clipboard (Microsoft Office)", (cmd) => { Popup_CommandHandler_OfficeClipboard(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Copy To Clipboard (Microsoft Office)", Command = command, IsEnabled = displayClipboard }; flyoutSubItem.Items.Add(flyoutItem); } //if (displayPaste) { var command = new FlyoutCommand("Paste", (cmd) => { Popup_CommandHandler_Paste(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Paste", Command = command, IsEnabled = displayPaste }; flyoutSubItem.Items.Add(flyoutItem); } } if (displayImport || displayExport) { var flyoutSubItem = new MenuFlyoutSubItem { Text = "Import/Export..." }; flyoutMenu.Items.Add(flyoutSubItem); //if (displayImport) { var command = new FlyoutCommand("Import", (cmd) => { Popup_CommandHandler_Import(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Import", Command = command, IsEnabled = displayImport }; flyoutSubItem.Items.Add(flyoutItem); } //if (displayExport) { var command = new FlyoutCommand("Export", (cmd) => { Popup_CommandHandler_Export(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Export", Command = command, IsEnabled = displayExport }; flyoutSubItem.Items.Add(flyoutItem); } } if (flyoutMenu.Items.Count > 0) { flyoutMenu.ShowAt(null, globalPos); } } }
public static Point GetEdgeEndpointOnEllipse(Point oVertexALocation, double dVertexARadiusWidth, double dVertexARadiusHeight, Point oVertexBLocation) { Debug.Assert(dVertexARadiusWidth >= 0); Debug.Assert(dVertexARadiusHeight >= 0); var dEdgeAngle = MathHelper.GetAngleBetweenPointsRadians(oVertexALocation, oVertexBLocation); return(new Point( oVertexALocation.X + (dVertexARadiusWidth * Math.Cos(dEdgeAngle)), oVertexALocation.Y - (dVertexARadiusHeight * Math.Sin(dEdgeAngle)) )); }
/// <summary> /// Update edge pointer position and angle /// </summary> public virtual Point Update(Point? position, Vector direction, double angle = 0d) { //var vecOffset = new Vector(direction.X * Offset.X, direction.Y * Offset.Y); if (DesiredSize.Width == 0 || DesiredSize.Height == 0 || !position.HasValue) return new Point(); var vecMove = new Vector(direction.X * DesiredSize.Width * .5, direction.Y * DesiredSize.Height * .5); position = new Point(position.Value.X - vecMove.X, position.Value.Y - vecMove.Y);// + vecOffset; if (!double.IsNaN(DesiredSize.Width) && DesiredSize.Width != 0 && !double.IsNaN(position.Value.X)) { LastKnownRectSize = new Rect(new Point(position.Value.X - DesiredSize.Width * .5, position.Value.Y - DesiredSize.Height * .5), DesiredSize); Arrange(LastKnownRectSize); } if(NeedRotation) RenderTransform = new RotateTransform { Angle = angle, CenterX = 0, CenterY = 0 }; return new Point(direction.X * ActualWidth, direction.Y * ActualHeight); }
public static Point GetEdgeEndpointOnDiamond(Point oVertexLocation, double mDHalfWidth, Point otherEndpoint) { // A diamond is just a rotated square, so the // GetEdgePointOnRectangle() can be used if the // diamond and the other vertex location are first rotated 45 degrees // about the diamond's center. var dHalfSquareWidth = mDHalfWidth / Math.Sqrt(2.0); var oRotatedDiamond = new Rect( oVertexLocation.X - dHalfSquareWidth, oVertexLocation.Y - dHalfSquareWidth, 2.0 * dHalfSquareWidth, 2.0 * dHalfSquareWidth ); var oMatrix = GetRotatedMatrix(oVertexLocation, 45); var oRotatedOtherVertexLocation = oMatrix.Transform(otherEndpoint); var oRotatedEdgeEndpoint = GetEdgeEndpointOnRectangle(oVertexLocation, oRotatedDiamond, oRotatedOtherVertexLocation); // Now rotate the computed edge endpoint in the other direction. oMatrix = GetRotatedMatrix(oVertexLocation, -45); return(oMatrix.Transform(oRotatedEdgeEndpoint)); // }
public void DrawLine(float sx, float sy, float ex, float ey, float w) { if (polyline != null) { var n = polylinePoints.Count; if (polylineLength == 0) { var sp = new Point (sx, sy); if (n == 0) { polylinePoints.Add (sp); n++; } else { polylinePoints[0] = sp; } polylineLength = 1; } var ep = new Point (ex, ey); if (polylineLength >= n) { polylinePoints.Add (ep); } else { polylinePoints[polylineLength] = ep; } polylineLength++; var s = polylineShape; if (s.Color != _currentColor) { s.Color = _currentColor; polyline.Stroke = _currentColor.GetBrush (); } if (s.Thickness != w) { s.Thickness = w; polyline.StrokeThickness = w; } } else { var s = GetNextShape(TypeId.Line); var line = (Line)s.Element; if (s.X != sx) { s.X = sx; line.X1 = sx; } if (s.Y != sy) { s.Y = sy; line.Y1 = sy; } if (s.Width != ex) { s.Width = ex; line.X2 = ex; } if (s.Height != ey) { s.Height = ey; line.Y2 = ey; } if (s.Color != _currentColor) { s.Color = _currentColor; line.Stroke = _currentColor.GetBrush(); } if (s.Thickness != w) { s.Thickness = w; line.StrokeThickness = w; } } }
private void DisplayContextualMenu(Windows.Foundation.Point globalPos) { var contentBlock = _lastSelectedBlock; var supportedTypes = _editor.SupportedAddBlockTypes; var supportedExports = _editor.GetSupportedExportMimeTypes(contentBlock); var supportedImportTypes = _editor.GetSupportedImportMimeTypes(contentBlock); var isContainer = contentBlock.Type == "Container"; var isRoot = contentBlock.Id == _editor.GetRootBlock().Id; var displayConvert = !isContainer && !_editor.IsEmpty(contentBlock); var displayAddBlock = supportedTypes != null && supportedTypes.Any() && isContainer; var displayAddImage = false; // supportedTypes != null && supportedTypes.Any() && isContainer; var displayRemove = !isRoot && !isContainer; var displayCopy = !isRoot && !isContainer; var displayPaste = supportedTypes != null && supportedTypes.Any() && isContainer; var displayImport = supportedImportTypes != null && supportedImportTypes.Any(); var displayExport = supportedExports != null && supportedExports.Any(); var displayOfficeClipboard = (supportedExports != null) && supportedExports.Contains(MimeType.OFFICE_CLIPBOARD); var flyoutMenu = new MenuFlyout(); if (displayConvert) { var command = new FlyoutCommand("Convert", (cmd) => { Popup_CommandHandler_Convert(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Convert", Command = command }; flyoutMenu.Items.Add(flyoutItem); } if (displayRemove) { var command = new FlyoutCommand("Remove", (cmd) => { Popup_CommandHandler_Remove(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Remove", Command = command }; flyoutMenu.Items.Add(flyoutItem); } if (displayCopy) { var command = new FlyoutCommand("Copy", (cmd) => { Popup_CommandHandler_Copy(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Copy", Command = command }; flyoutMenu.Items.Add(flyoutItem); } if (displayPaste) { var command = new FlyoutCommand("Paste", (cmd) => { Popup_CommandHandler_Paste(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Paste", Command = command }; flyoutMenu.Items.Add(flyoutItem); } if (displayOfficeClipboard) { var command = new FlyoutCommand("Copy To Clipboard (Microsoft Office)", (cmd) => { Popup_CommandHandler_OfficeClipboard(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Copy To Clipboard (Microsoft Office)", Command = command }; flyoutMenu.Items.Add(flyoutItem); } if (displayAddBlock || displayAddImage) { var flyoutSubItem = new MenuFlyoutSubItem { Text = "Add..." }; if (displayAddBlock) { for (var i = 0; i < supportedTypes.Count(); ++i) { var command = new FlyoutCommand(supportedTypes[i], (cmd) => { Popup_CommandHandler_AddBlock(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Add " + supportedTypes[i], Command = command }; flyoutSubItem.Items.Add(flyoutItem); } } if (displayAddImage) { var command = new FlyoutCommand("Image", (cmd) => { Popup_CommandHandler_AddImage(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Add Image", Command = command }; flyoutSubItem.Items.Add(flyoutItem); } flyoutMenu.Items.Add(flyoutSubItem); } if (displayImport || displayExport) { var flyoutSubItem = new MenuFlyoutSubItem { Text = "Import/Export..." }; if (displayImport) { var command = new FlyoutCommand("Import", (cmd) => { Popup_CommandHandler_Import(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Import", Command = command }; flyoutSubItem.Items.Add(flyoutItem); } if (displayExport) { var command = new FlyoutCommand("Export", (cmd) => { Popup_CommandHandler_Export(cmd); }); var flyoutItem = new MenuFlyoutItem { Text = "Export", Command = command }; flyoutSubItem.Items.Add(flyoutItem); } flyoutMenu.Items.Add(flyoutSubItem); } flyoutMenu.ShowAt(null, globalPos); }
/// <summary> /// Set attached coordinates X and Y /// </summary> /// <param name="pt"></param> /// <param name="alsoFinal"></param> public void SetPosition(Point pt, bool alsoFinal = true) { GraphAreaBase.SetX(this, pt.X, alsoFinal); GraphAreaBase.SetY(this, pt.Y, alsoFinal); }
private async Task FocusAtPoint(Point location) { if (PhotoCaptureDevice.IsFocusRegionSupported(PerfectCamera.DataContext.Instance.SensorLocation) && _focusSemaphore.WaitOne(0)) { try { _focusDisplayTimer.Stop(); FocusAnimation.Stop(); Thickness margin = new Thickness(location.X - 45, location.Y - 45, 0, 0); FocusImage.Margin = margin; FocusImage.Visibility = System.Windows.Visibility.Visible; FocusAnimation.Begin(); // Get tap coordinates as a foundation point Windows.Foundation.Point tapPoint = new Windows.Foundation.Point(location.X, location.Y); double xRatio = VideoCanvas.ActualHeight / PerfectCamera.DataContext.Instance.PreviewResolution.Width; double yRatio = VideoCanvas.ActualWidth / PerfectCamera.DataContext.Instance.PreviewResolution.Height; // adjust to center focus on the tap point Windows.Foundation.Point displayOrigin = new Windows.Foundation.Point( tapPoint.Y - _focusRegionSize.Width / 2, (VideoCanvas.ActualWidth - tapPoint.X) - _focusRegionSize.Height / 2); // adjust for resolution difference between preview image and the canvas Windows.Foundation.Point viewFinderOrigin = new Windows.Foundation.Point(displayOrigin.X / xRatio, displayOrigin.Y / yRatio); Windows.Foundation.Rect focusrect = new Windows.Foundation.Rect(viewFinderOrigin, _focusRegionSize); // clip to preview resolution Windows.Foundation.Rect viewPortRect = new Windows.Foundation.Rect(0, 0, PerfectCamera.DataContext.Instance.PreviewResolution.Width, PerfectCamera.DataContext.Instance.PreviewResolution.Height); focusrect.Intersect(viewPortRect); Camera.FocusRegion = focusrect; CameraFocusStatus status = await Camera.FocusAsync(); if (status == CameraFocusStatus.Locked) { _manuallyFocused = true; Camera.SetProperty(KnownCameraPhotoProperties.LockedAutoFocusParameters, AutoFocusParameters.Exposure & AutoFocusParameters.Focus & AutoFocusParameters.WhiteBalance); } else { _manuallyFocused = false; Camera.SetProperty(KnownCameraPhotoProperties.LockedAutoFocusParameters, AutoFocusParameters.None); } } catch (Exception ex) { Debug.WriteLine("ex: {0}", ex.Message); } _focusSemaphore.Release(); } }
private void UpdateSourceEpData(Point from, Point to) { var dir = MathHelper.GetDirection(from, to); _edgePointerForSource.Update(from, dir, _edgePointerForSource.NeedRotation ? -MathHelper.GetAngleBetweenPoints(from, to).ToDegrees() : 0); }
public static int GetIntersectionPoint(Rect r, Point a, Point b, out Point pt) { var start = new Point(a.X, a.Y); var codeA = GetIntersectionData(r, a); var codeB = GetIntersectionData(r, b); while (!codeA.IsInside() || !codeB.IsInside()) { if (codeA.SameSide(codeB)) { pt = new Point(); return -1; } sides code; Point c; if (!codeA.IsInside()) { code = codeA; c = a; } else { code = codeB; c = b; } if (code.Left) { c.Y += (a.Y - b.Y) * (r.Left - c.X) / (a.X - b.X); c.X = r.Left; } else if (code.Right) { c.Y += (a.Y - b.Y) * (r.Right - c.X) / (a.X - b.X); c.X = r.Right; } else if (code.Bottom) { c.X += (a.X - b.X) * (r.Bottom - c.Y) / (a.Y - b.Y); c.Y = r.Bottom; } else if (code.Top) { c.X += (a.X - b.X) * (r.Top - c.Y) / (a.Y - b.Y); c.Y = r.Top; } if (code == codeA) { a = c; codeA = GetIntersectionData(r, a); } else { b = c; codeB = GetIntersectionData(r, b); } } pt = GetCloserPoint(start, a, b); return 0; }
void PositionDebugMessage(Windows.Foundation.Point point) { DebugMessage("Position: x=[" + point.X + "] y=[" + point.Y + "]"); }
private async void RenderLenseContentAsync(Point center) { _lastLenseCenterForRendering = center; if (!_renderingLenseContent) { _renderingLenseContent = true; HighResolutionCropImage.Visibility = Visibility.Collapsed; do { center = _lastLenseCenterForRendering; // Scale between the rendered image element and the bitmap displayed in it var previewToHighResolutionCropScale = _info.ImageSize.Width / PreviewImage.ActualWidth; var screenScaleFactor = App.Current.Host.Content.ScaleFactor / 100.0; // Find crop area top left coordinate in the actual high resolution image var topLeftX = center.X * previewToHighResolutionCropScale - LenseContent.Width / 2 * screenScaleFactor / DIGITAL_MAGNIFICATION; var topLeftY = center.Y * previewToHighResolutionCropScale - LenseContent.Height / 2 * screenScaleFactor / DIGITAL_MAGNIFICATION; // Find crop area bottom right coordinate in the actual high resolution image var bottomRightX = center.X * previewToHighResolutionCropScale + LenseContent.Width / 2 * screenScaleFactor / DIGITAL_MAGNIFICATION; var bottomRightY = center.Y * previewToHighResolutionCropScale + LenseContent.Height / 2 * screenScaleFactor / DIGITAL_MAGNIFICATION; var topLeft = new Windows.Foundation.Point(topLeftX, topLeftY); var bottomRight = new Windows.Foundation.Point(bottomRightX, bottomRightY); _reframingFilter.ReframingArea = new Windows.Foundation.Rect(topLeft, bottomRight); await _renderer.RenderAsync(); } while (_lastLenseCenterForRendering != center); _highResolutionCropBitmap.Invalidate(); HighResolutionCropImage.Visibility = Visibility.Visible; _renderingLenseContent = false; } }
void SelectionRect_ManipulationDelta(object sender, Windows.UI.Xaml.Input.ManipulationDeltaRoutedEventArgs e) { // Get current position of selection's bounding box var curPos = new Windows.Foundation.Point( Windows.UI.Xaml.Controls.Canvas.GetLeft(SelectionRect), Windows.UI.Xaml.Controls.Canvas.GetTop(SelectionRect) ); // Compute new position, making sure that the bounding box does not go outside the InkingArea var newPos = new Windows.Foundation.Point( Math.Max(0, Math.Min(curPos.X + e.Delta.Translation.X, InkingArea.ActualWidth - SelectionRect.Width)), Math.Max(0, Math.Min(curPos.Y + e.Delta.Translation.Y, InkingArea.ActualHeight - SelectionRect.Height)) ); // Compute the actual translation to pass to InkManager.MoveSelected var translation = new Windows.Foundation.Point( newPos.X - curPos.X, newPos.Y - curPos.Y ); if (Math.Abs(translation.X) > 0 || Math.Abs(translation.Y) > 0) { // Move the selection's bounding box Windows.UI.Xaml.Controls.Canvas.SetLeft(SelectionRect, newPos.X); Windows.UI.Xaml.Controls.Canvas.SetTop(SelectionRect, newPos.Y); // Move selected ink inkManager.MoveSelected(translation); // Re-render everything renderer.Clear(); renderer.AddInk(inkManager.GetStrokes()); renderer.UpdateSelection(); } e.Handled = true; }
public static Rect ToRect(this Size size, Point point) { return(new Rect(point, size)); }
public void Vector2FromPointTest() { var point = new Windows.Foundation.Point(23, 42); Vector2 result = point.ToVector2(); Assert.AreEqual(23.0f, result.X); Assert.AreEqual(42.0f, result.Y); }
/// <summary> /// Shows the context menu at the specified client coordinates. /// </summary> /// <param name="invocationPoint">The coordinates (in DIPs), relative to the window, of the user's finger or mouse pointer when the oncontextmenu event fired. /// The menu is placed above and centered on this point.</param> /// <returns>An object that represents the asynchronous operation. /// For more on the async pattern, see Asynchronous programming in the Windows Runtime.</returns> public Task<IUICommand> ShowAsync(Point invocationPoint) { #if WINDOWS_UWP return Task.Run<IUICommand>(async () => { foreach(IUICommand command in Commands) { _menu.Commands.Add(new Windows.UI.Popups.UICommand(command.Label, new Windows.UI.Popups.UICommandInvokedHandler((c2) => { command.Invoked?.Invoke(command); }), command.Id)); } Windows.Foundation.Point p = new Windows.Foundation.Point(invocationPoint.X, invocationPoint.Y); var c = await _menu.ShowAsync(p); return c == null ? null : new UICommand(c.Label, new UICommandInvokedHandler((c2) => { c2.Invoked?.Invoke(c2); }), c.Id); }); #else return ShowForSelectionAsync(new Rect(invocationPoint.X, invocationPoint.Y,0,0), Placement.Default); #endif }
/// <summary> /// Implementation of <see cref="FilterManipulation"/> that forces the center of mass of the /// manipulation target to remain inside its container. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> public static void ClampCenterOfMass(object sender, Manipulations.FilterManipulationEventArgs args) { var inputProcessor = sender as Manipulations.InputProcessor; var target = inputProcessor.Target; var container = inputProcessor.Reference; // Get the bounding box and the center of mass of the manipulation target, // expressed in the coordinate system of its container var rect = target.RenderTransform.TransformBounds( new Windows.Foundation.Rect(0, 0, target.ActualWidth, target.ActualHeight)); var centerOfMass = new Windows.Foundation.Point { X = rect.Left + (rect.Width / 2), Y = rect.Top + (rect.Height / 2) }; // Apply delta transform to the center of mass var transform = new Windows.UI.Xaml.Media.CompositeTransform { CenterX = args.Pivot.X, CenterY = args.Pivot.Y, Rotation = args.Delta.Rotation, ScaleX = args.Delta.Scale, ScaleY = args.Delta.Scale, TranslateX = args.Delta.Translation.X, TranslateY = args.Delta.Translation.Y }; var transformedCenterOfMass = transform.TransformPoint(centerOfMass); // Reset the transformation if the transformed center of mass falls outside the container if (transformedCenterOfMass.X < 0 || transformedCenterOfMass.X > container.ActualWidth || transformedCenterOfMass.Y < 0 || transformedCenterOfMass.Y > container.ActualHeight) { args.Delta = new Windows.UI.Input.ManipulationDelta { Rotation = 0F, Scale = 1F, Translation = new Windows.Foundation.Point(0, 0) }; } }
private Windows.Foundation.Rect GetElementRect(FrameworkElement element) { Windows.UI.Xaml.Media.GeneralTransform buttonTransform = element.TransformToVisual(null); Windows.Foundation.Point point = buttonTransform.TransformPoint(new Windows.Foundation.Point()); return(new Windows.Foundation.Rect(point, new Windows.Foundation.Size(element.ActualWidth, element.ActualHeight))); }