public static void SplitGeometry(Geometry geo, Point pt1, Point pt2, out PathGeometry leftGeo, out PathGeometry rightGeo) { double c = 360.0 + 90.0 - (180.0 / Math.PI * Math.Atan2(pt2.Y - pt1.Y, pt2.X - pt1.X)); var t = new TransformGroup(); t.Children.Add(new TranslateTransform(-pt1.X, -pt1.Y)); t.Children.Add(new RotateTransform(c)); var i = t.Inverse; leftGeo = new PathGeometry(); rightGeo = new PathGeometry(); foreach (var figure in geo.GetFlattenedPathGeometry().Figures) { var left = new List <Point>(); var right = new List <Point>(); var lastPt = t.Transform(figure.StartPoint); foreach (PolyLineSegment segment in figure.Segments) { foreach (var currentPtOrig in segment.Points) { var currentPt = t.Transform(currentPtOrig); ProcessLine(lastPt, currentPt, left, right); lastPt = currentPt; } } ProcessFigure(left, i, leftGeo); ProcessFigure(right, i, rightGeo); } }
protected void DrawGraphicItem(NVCO.Text textItem) { var scrnPt = xformGroup_all.Transform(textItem.Origin); var aTextBox = new TextBox(); aTextBox.FontFamily = new FontFamily("Arial"); Double candidateFontSize = textItem.Height * 72 / this.myCadViewPort.ScaleVector.y; if (candidateFontSize < 3) { candidateFontSize = 3; } aTextBox.FontSize = candidateFontSize; aTextBox.BorderBrush = Brushes.Transparent; aTextBox.Background = Brushes.Transparent; aTextBox.Margin = new Thickness(0, 0, 0, 0); aTextBox.BorderThickness = new Thickness(1, 1, 1, 1); if (aTextBox.FontSize > 10.6) { aTextBox.Padding = new Thickness(0, 0, 0, 0); } else { aTextBox.Padding = new Thickness(-6, -6, -6, -6); } setSymbologyText(aTextBox, textItem); aTextBox.Text = textItem.Content; //aTextBox.ToolTip = textItem.GetToolTip(); aTextBox.RenderTransformOrigin = new WIN.Point(0, 0); var rotAboutPt = xformGroup_all.Transform(textItem.Origin); var xfrmGrp = new TransformGroup(); if (this.myCadViewPort.Rotation.getAsDegreesDouble() != 0.0) { xfrmGrp.Children.Add( new RotateTransform( -this.myCadViewPort.Rotation.getAsDegreesDouble() ) ); } if (textItem.Rotation.getAsDegreesDouble() != 0.0) { xfrmGrp.Children.Add( new RotateTransform( -1 * textItem.Rotation.getAsDegreesDouble() ) ); } aTextBox.RenderTransform = xfrmGrp; Canvas.SetLeft(aTextBox, scrnPt.X); /// this.myCadViewPort.ScaleVector.x); Canvas.SetTop(aTextBox, scrnPt.Y); /// this.myCadViewPort.ScaleVector.y); this.Children.Add(aTextBox); }
private Point GetTouchPosition(int deviceId) { if (_points != null) { return(_transform.Transform( _points.FirstOrDefault(p => p.TouchDevice.Id == deviceId).Position)); } if (_mockPoints != null) { return(_transform.Transform( _mockPoints.FirstOrDefault(p => p.TouchDevice.Id == deviceId).Position)); } return(new Point()); }
public static NVCFND.Point Transform(this TransformGroup xfrm, NVCFND.Point inPoint) { Point intermediatePoint = new Point(inPoint.x, inPoint.y); var nxtIntPt = xfrm.Transform(intermediatePoint); return(new NVCFND.Point(nxtIntPt.X, nxtIntPt.Y)); }
//conversions /// <summary>Convert map coordinates to local (relative to mapviewer)</summary> /// <param name="mapPosition"></param> /// <returns></returns> public Point FromMapToLocal(Point mapPosition) { var bitmapPosition = geoImage.FromMapToBitmap(mapPosition); var localPosition = mapTransformGroup.Transform(bitmapPosition); return(localPosition); }
public static WIN.Point Transform (this TransformGroup xfg, NVCFND.Point ptPreXfrm ) { pt = new WIN.Point(ptPreXfrm.x, ptPreXfrm.y); return(xfg.Transform(pt)); }
protected override void OnRender(DrawingContext drawingContext) { var time = DateTime.Now; var delta = time - lastTime; lastTime = time; progress += delta.TotalSeconds / 2f; if (progress > 1) { progress = 0; } var squareWidth = Math.Min(ActualWidth, ActualHeight); squareWidth = Math.Min(256, squareWidth); var finalPipSize = squareWidth * 0.07; var centrePoint = new Point(ActualWidth / 2, ActualHeight / 2); double ringRadius = (squareWidth / 2) - (finalPipSize * 1.1) - (squareWidth * 0.1); var progressVector = (Vector) new RotateTransform(360.0 * progress, 0, 0).Transform(new Point(0, -1)); var indicatorPosition = new TranslateTransform(centrePoint.X, centrePoint.Y - ringRadius); for (int i = 0; i < PipCount; i++) { var transform = new TransformGroup(); transform.Children.Add(indicatorPosition); transform.Children.Add(new RotateTransform(360.0 * i * PipIncrement, centrePoint.X, centrePoint.Y)); var progressDot = Vector.Multiply(progressVector, (Vector) new RotateTransform(360.0 * i * PipIncrement, 0, 0).Transform(new Point(0, -1))); double pulse = 1; if (progressDot > 0.8) { pulse += ((progressDot - 0.8) / 0.2) * 0.5; } var pipRadius = (finalPipSize * pulse) / 2; drawingContext.DrawEllipse(Brushes.DarkGreen, null, transform.Transform(new Point()), pipRadius, pipRadius); } if (!string.IsNullOrEmpty(Text) && ActualWidth > 0 && ActualHeight > 0) { var text = new FormattedText(Text, System.Globalization.CultureInfo.CurrentUICulture, GetFlowDirection(this), new Typeface(TextBlock.GetFontFamily(this), TextBlock.GetFontStyle(this), TextBlock.GetFontWeight(this), TextBlock.GetFontStretch(this)), TextBlock.GetFontSize(this), Brushes.LightGray, 1) { MaxTextWidth = ActualWidth, MaxTextHeight = ActualHeight, TextAlignment = TextAlignment.Center, Trimming = TextTrimming.WordEllipsis }; drawingContext.DrawText(text, new Point(0, centrePoint.Y - (text.Height / 2))); } }
private static Canvas DrawVoronoi_Tiled(VoronoiResult2D voronoi, SOMNode[] nodes, ISOMInput[][] images, int imageWidth, int imageHeight, int tileWidth, int tileHeight, Action <DrawTileArgs> drawTile, BlobEvents events) { #region transform var aabb = Math2D.GetAABB(voronoi.EdgePoints); TransformGroup transform = new TransformGroup(); transform.Children.Add(new TranslateTransform(-aabb.Item1.X, -aabb.Item1.Y)); transform.Children.Add(new ScaleTransform(imageWidth / (aabb.Item2.X - aabb.Item1.X), imageHeight / (aabb.Item2.Y - aabb.Item1.Y))); #endregion Canvas retVal = new Canvas(); for (int cntr = 0; cntr < voronoi.ControlPoints.Length; cntr++) { #region polygon Polygon polygon = new Polygon(); if (voronoi.EdgesByControlPoint[cntr].Length < 3) { throw new ApplicationException("Expected at least three edge points"); } Edge2D[] edges = voronoi.EdgesByControlPoint[cntr].Select(o => voronoi.Edges[o]).ToArray(); Point[] edgePoints = Edge2D.GetPolygon(edges, 1d); edgePoints = edgePoints. Select(o => transform.Transform(o)). ToArray(); foreach (Point point in edgePoints) { polygon.Points.Add(point); } polygon.Fill = GetTiledSamples(edgePoints, images[cntr], nodes[cntr], tileWidth, tileHeight, drawTile); polygon.Stroke = new SolidColorBrush(UtilityWPF.GetRandomColor(64, 192)); polygon.StrokeThickness = 2; polygon.Tag = Tuple.Create(nodes[cntr], images[cntr]); if (events != null) { if (events.MouseMove != null && events.MouseLeave != null) { polygon.MouseMove += Polygon2D_MouseMove; polygon.MouseLeave += Polygon2D_MouseLeave; } if (events.Click != null) { polygon.MouseUp += Polygon_MouseUp; } } retVal.Children.Add(polygon); #endregion } return(retVal); }
private static Canvas DrawVoronoi_Blobs(VoronoiResult2D voronoi, Color[] colors, SOMNode[] nodes, ISOMInput[][] inputsByNode, int imageWidth, int imageHeight, BlobEvents events) { const double MARGINPERCENT = 1.05; // Analyze size ratios double[] areas = AnalyzeVoronoiCellSizes(voronoi, inputsByNode); #region transform var aabb = Math2D.GetAABB(voronoi.EdgePoints); aabb = Tuple.Create((aabb.Item1.ToVector() * MARGINPERCENT).ToPoint(), (aabb.Item2.ToVector() * MARGINPERCENT).ToPoint()); TransformGroup transform = new TransformGroup(); transform.Children.Add(new TranslateTransform(-aabb.Item1.X, -aabb.Item1.Y)); transform.Children.Add(new ScaleTransform(imageWidth / (aabb.Item2.X - aabb.Item1.X), imageHeight / (aabb.Item2.Y - aabb.Item1.Y))); #endregion Canvas retVal = new Canvas(); retVal.Effect = new DropShadowEffect() { Color = Colors.Gray, Opacity = .2, BlurRadius = 5, Direction = 0, ShadowDepth = 0, }; for (int cntr = 0; cntr < voronoi.ControlPoints.Length; cntr++) { #region polygon Polygon polygon = new Polygon(); if (voronoi.EdgesByControlPoint[cntr].Length < 3) { throw new ApplicationException("Expected at least three edge points"); } Edge2D[] edges = voronoi.EdgesByControlPoint[cntr].Select(o => voronoi.Edges[o]).ToArray(); Point[] edgePoints = Edge2D.GetPolygon(edges, 1d); // Resize to match the desired area edgePoints = ResizeConvexPolygon(edgePoints, areas[cntr]); // Convert into a smooth blob BezierSegment3D[] bezier = BezierUtil.GetBezierSegments(edgePoints.Select(o => o.ToPoint3D()).ToArray(), .25, true); edgePoints = BezierUtil.GetPath(75, bezier). Select(o => o.ToPoint2D()). ToArray(); // Transform to canvas coords edgePoints = edgePoints. Select(o => transform.Transform(o)). ToArray(); foreach (Point point in edgePoints) { polygon.Points.Add(point); } polygon.Fill = new SolidColorBrush(colors[cntr]); polygon.Stroke = null; // new SolidColorBrush(UtilityWPF.OppositeColor(colors[cntr], false)); polygon.StrokeThickness = 1; polygon.Tag = Tuple.Create(events, nodes[cntr], inputsByNode[cntr]); if (events != null) { if (events.MouseMove != null && events.MouseLeave != null) { polygon.MouseMove += Polygon2D_MouseMove; polygon.MouseLeave += Polygon2D_MouseLeave; } if (events.Click != null) { polygon.MouseUp += Polygon_MouseUp; } } retVal.Children.Add(polygon); #endregion } return(retVal); }
void UpdatePointer(Point pos) { if (data != null && data.AllSeries.Count > 0 && scale != null && scale.ScaleX > 0) { if (selectedSeries == null) { selectedSeries = data.AllSeries[data.AllSeries.Count - 1]; } Point legendPos = this.TransformToDescendant(legend).Transform(pos); Rect legendArea = new Rect(0, 0, legend.ActualWidth, legend.ActualHeight); bool insideLegend = (legendArea.Contains(legendPos)); if (pointer == null) { PathGeometry diamond = new PathGeometry(); PathFigure figure = new PathFigure(); diamond.Figures.Add(figure); figure.IsClosed = true; figure.IsFilled = true; figure.StartPoint = new Point(0, -5); figure.Segments.Add(new LineSegment(new Point(5, 0), true)); figure.Segments.Add(new LineSegment(new Point(0, 5), true)); figure.Segments.Add(new LineSegment(new Point(-5, 0), true)); pointer = new Path() { Data = diamond, Fill = Brushes.Red }; this.Children.Add(pointer); } if (tooltip == null) { tooltip = new Border(); tooltip.Padding = new Thickness(2); tooltip.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; tooltip.VerticalAlignment = System.Windows.VerticalAlignment.Top; tooltip.BorderBrush = Brushes.Black; tooltip.BorderThickness = new Thickness(1); tooltip.Background = Brushes.White; label = new TextBlock(); label.Foreground = Brushes.Black; tooltip.Child = label; this.Children.Add(tooltip); } ChartSeries series = selectedSeries; var values = series.Values; int i = (int)(pos.X / scale.ScaleX); if (i >= 0 && i < values.Count) { ChartValue v = values[i]; Selected = v; label.Text = v.Label; if (insideLegend) { tooltip.Visibility = System.Windows.Visibility.Hidden; } else { tooltip.UpdateLayout(); double tipPositionX = pos.X; if (tipPositionX + tooltip.ActualWidth > this.ActualWidth) { tipPositionX = this.ActualWidth - tooltip.ActualWidth; } double tipPositionY = pos.Y - label.ActualHeight - 4; if (tipPositionY < 0) { tipPositionY = 0; } tooltip.Margin = new Thickness(tipPositionX, tipPositionY, 0, 0); tooltip.Visibility = System.Windows.Visibility.Visible; } double value = v.Value; if (series.Flipped) { value = -value; } Point pointerPosition = transform.Transform(new Point(i, value)); pointer.RenderTransform = new TranslateTransform(pointerPosition.X, pointerPosition.Y); pointer.Visibility = System.Windows.Visibility.Visible; } else { tooltip.Visibility = System.Windows.Visibility.Hidden; pointer.Visibility = System.Windows.Visibility.Hidden; } } else { // todo } }
private void LayoutGraph(Size size) { PathGeometry path = LineGraph.Data as PathGeometry; if (path != null && data != null && points != null) { Rect bounds = this.bounds; double yw = YAxis.RenderSize.Width; var w = size.Width - yw - 20; var h = size.Height - 80; if (zoomToFit) { zoom = w / bounds.Width; } var ymargin = TopMargin; if (bounds != Rect.Empty && bounds.Height != 0) { TransformGroup g = new TransformGroup(); g.Children.Add(new TranslateTransform(0, -bounds.Top)); g.Children.Add(new ScaleTransform(zoom, -h / bounds.Height)); g.Children.Add(new TranslateTransform(LeftMargin, h + ymargin)); List <Point> pts = new List <Point>(); foreach (Point p in points) { Point t = g.Transform(p); pts.Add(t); } scaled = pts; LineGraph.Data = CreateGeometry(pts); Rect newBounds = g.TransformBounds(bounds); Border.Width = newBounds.Width; Border.Height = newBounds.Height; double xMean = Mean(from p in pts select p.X); double yMean = Mean(from p in pts select p.Y); double xVariance = Variance(from p in pts select p.X); double yVariance = Variance(from p in pts select p.Y); double covariance = Covariance(pts); double b = covariance / xVariance; double a = yMean - (b * xMean); TrendLine.X1 = 0; TrendLine.X2 = w; TrendLine.Y1 = a; TrendLine.Y2 = a + (b * w); // now run on the raw data xMean = Mean(from p in points select p.X); yMean = Mean(from p in points select p.Y); xVariance = Variance(from p in points select p.X); yVariance = Variance(from p in points select p.Y); covariance = Covariance(points); double realb = covariance / xVariance; double reala = yMean - (b * xMean); LineLabel.Content = string.Format("y = {0} + {1}x", reala.ToString("N0"), realb.ToString("N0")); g = new TransformGroup(); g.Children.Add(new RotateTransform(Math.Atan((TrendLine.Y2 - TrendLine.Y1) / (TrendLine.X2 - TrendLine.X2)))); g.Children.Add(new TranslateTransform(0, a - 20)); LineLabel.RenderTransform = g; } } }
public Point TransformXY(Point source) { return(_csTransform.Transform(source)); }
public Point PixelToTopLeftTileEdge(Point point) { Point edgePoint = pixelToTile.Transform(point); return(pixelToTile.Inverse.Transform(new Point((int)edgePoint.X, (int)edgePoint.Y))); }
/// <summary> /// Rotates this <see cref="PngFrame"/> with a given rotation angle. /// </summary> /// <param name="rotationDegrees">Rotation angle in degrees.</param> /// <param name="scalingMode"><see cref="BitmapScalingMode"/> used for rendering the rotated frame. Defaults to <see cref="BitmapScalingMode.NearestNeighbor"/>.</param> /// <exception cref="InvalidOperationException" /> /// <exception cref="ArgumentException" /> /// <exception cref="NotSupportedException" /> public void RotateFrame(double rotationDegrees, BitmapScalingMode scalingMode = BitmapScalingMode.NearestNeighbor) { var rotationRad = rotationDegrees / 180.0 * Math.PI; var frame = this.BitmapFrame; var transform = new RotateTransform(rotationDegrees); var w = frame.PixelWidth; var h = frame.PixelHeight; var newW = (int)(Math.Abs(w * Math.Sin(rotationRad)) + Math.Abs(h * Math.Cos(rotationRad))); var newH = (int)(Math.Abs(w * Math.Cos(rotationRad)) + Math.Abs(h * Math.Sin(rotationRad))); if (newW > 256) { throw new InvalidOperationException(nameof(this.Width) + " is too big to be rotated."); } if (newH > 256) { throw new InvalidOperationException(nameof(this.Height) + " is too big to be rotated."); } transform.CenterX = w / 2; transform.CenterY = h / 2; var transformGroup = new TransformGroup(); transformGroup.Children.Add(transform); transformGroup.Children.Add(new TranslateTransform((newW - w) / 2.0, (newH - h) / 2)); var origHotspot = new Point(this.HLeft, this.HTop); var transformedHotspot = transformGroup.Transform(origHotspot); var image = new Image() { Source = frame, RenderTransform = transformGroup, Width = w, Height = h, Stretch = Stretch.None, UseLayoutRounding = false, SnapsToDevicePixels = false, }; RenderOptions.SetBitmapScalingMode(image, scalingMode); image.Arrange(new Rect(0, 0, w, h)); var newRect = new Rect(0, 0, newW, newH); var dv = new DrawingVisual(); using (var ctx = dv.RenderOpen()) { var vb = new VisualBrush(image); vb.TileMode = TileMode.None; vb.ViewboxUnits = BrushMappingMode.Absolute; vb.Viewbox = newRect; ctx.DrawRectangle(vb, null, newRect); } var resultSource = new RenderTargetBitmap(newW, newH, 96, 96, PixelFormats.Pbgra32); resultSource.Render(dv); this.HLeft = (ushort)transformedHotspot.X; this.HTop = (ushort)transformedHotspot.Y; this.Width = (byte)newW; this.Height = (byte)newH; this._BitmapFrame = BitmapFrame.Create(resultSource); this._PngFile = null; }
/// <summary> /// If detections are turned on, draw all bounding boxes relative to 0,0 and contrained by width and height within the provided /// The width/height should be the actual width/height of the image (also located at 0,0) as it appears in the canvas , which is required if the bounding boxes are to be drawn in the correct places /// if the image has a margin, that should be included as well otherwise set it to 0 /// The canvas should also be cleared of prior bounding boxes before this is invoked. /// </summary> /// <param name="canvas"></param> public bool DrawBoundingBoxesInCanvas(Canvas canvas, double width, double height, int margin = 0, TransformGroup transformGroup = null) { if (canvas == null) { return(false); } // Remove existing bounding boxes, if any. // Note that we do this even if detections may not exist, as we need to clear things if the user had just toggled detections off if (GlobalReferences.DetectionsExists == false || Keyboard.IsKeyDown(Key.H)) { // As detection don't exist, there won't be any bounding boxes to draw. return(false); } // Max Confidence is over all bounding boxes, regardless of the categories. // So we just use it as a short cut, i.e., if none of the bounding boxes are above the threshold, we can abort. // Also, we add a slight correction value to the MaxConfidence, so confidences near the threshold will still appear. double correction = 0.005; if (this.MaxConfidence + correction < Util.GlobalReferences.TimelapseState.BoundingBoxDisplayThreshold && this.MaxConfidence + correction < Util.GlobalReferences.TimelapseState.BoundingBoxThresholdOveride) { // Ignore any bounding box that is below the desired confidence threshold for displaying it. // Note that the BoundingBoxDisplayThreshold is the user-defined default set in preferences, while the BoundingBoxThresholdOveride is the threshold // determined in the select dialog. For example, if (say) the preference setting is .6 but the selection is at .4 confidence, then we should // show bounding boxes when the confidence is .4 or more. return(false); } foreach (BoundingBox bbox in this.Boxes) { if (bbox.Confidence + correction < Util.GlobalReferences.TimelapseState.BoundingBoxDisplayThreshold && bbox.Confidence + correction < Util.GlobalReferences.TimelapseState.BoundingBoxThresholdOveride) { // Ignore any bounding box that is below the desired confidence threshold for displaying it. // Note that the BoundingBoxDisplayThreshold is the user-defined default set in preferences, while the BoundingBoxThresholdOveride is the threshold // determined in the select dialog. For example, if (say) the preference setting is .6 but the selection is at .4 confidence, then we should // show bounding boxes when the confidence is .4 or more. continue; } // Create a bounding box Rectangle rect = new Rectangle(); SolidColorBrush brush; bool colorblind = Util.GlobalReferences.TimelapseState.BoundingBoxColorBlindFriendlyColors; byte opacity = colorblind ? (byte)255 : (byte)Math.Round(255 * bbox.Confidence); switch (bbox.DetectionCategory) { // The color and opacity of the bounding box depends upon its category and whether we are using color-blind friendly colors case "0": // In the current implementation, the first category is usually assigned to 'Empty', so this will likely never appear. brush = Util.ColorsAndBrushes.SolidColorBrushFromColor(Colors.LavenderBlush, opacity); break; case "1": brush = Util.ColorsAndBrushes.SolidColorBrushFromColor(Colors.DeepSkyBlue, opacity); break; case "2": brush = (colorblind) ? Util.ColorsAndBrushes.SolidColorBrushFromColor(Colors.Yellow) : Util.ColorsAndBrushes.SolidColorBrushFromColor(Colors.Red, opacity); break; case "3": brush = Util.ColorsAndBrushes.SolidColorBrushFromColor(Colors.White, opacity); break; default: brush = Util.ColorsAndBrushes.SolidColorBrushFromColor(Colors.PaleGreen, opacity); break; } rect.Stroke = brush; // Set the stroke thickness, which depends upon the size of the available height int stroke_thickness = Math.Min(width, height) > 400 ? 4 : 2; rect.StrokeThickness = stroke_thickness; Point screenPositionTopLeft; Point screenPositionBottomRight; if (transformGroup == null) { // The image is not being transformed. // Calculate the actual position of the bounding box from the ratios screenPositionTopLeft = BoundingBox.ConvertRatioToPoint(bbox.Rectangle.Left, bbox.Rectangle.Top, width, height); screenPositionBottomRight = BoundingBox.ConvertRatioToPoint(bbox.Rectangle.Left + bbox.Rectangle.Width, bbox.Rectangle.Top + bbox.Rectangle.Height, width, height); } else { // The image is transformed, so we have to apply that transformation to the bounding boxes screenPositionTopLeft = transformGroup.Transform(BoundingBox.ConvertRatioToPoint(bbox.Rectangle.Left, bbox.Rectangle.Top, width, height)); screenPositionBottomRight = transformGroup.Transform(BoundingBox.ConvertRatioToPoint(bbox.Rectangle.Left + bbox.Rectangle.Width, bbox.Rectangle.Top + bbox.Rectangle.Height, width, height)); } // Adjust the offset by any margin value (which could be 0) screenPositionTopLeft.X += margin; screenPositionTopLeft.Y += margin; Point screenPostionWidthHeight = new Point(screenPositionBottomRight.X - screenPositionTopLeft.X, screenPositionBottomRight.Y - screenPositionTopLeft.Y); // We also adjust the rect width and height to take into account the stroke thickness, to avoid the stroke overlapping the contained item // as otherwise the border thickness would overlap with the entity in the bounding box) rect.Width = screenPostionWidthHeight.X + (2 * stroke_thickness); rect.Height = screenPostionWidthHeight.Y + (2 * stroke_thickness); // Now add the rectangle to the canvas, also adjusting for the stroke thickness. Canvas.SetLeft(rect, screenPositionTopLeft.X - stroke_thickness); Canvas.SetTop(rect, screenPositionTopLeft.Y - stroke_thickness); canvas.Children.Add(rect); canvas.Tag = Constant.MarkableCanvas.BoundingBoxCanvasTag; // Bounding box labelling: Category plus confidence (to two decimal places or epsilon) // Use the primary detection category if there are no classifications, // The bboxLabel contains just the top-ranked classification category + its confidence // the bboxTextBlock contains all predicted items + their confidence as a list string bboxLabel = (bbox.Classifications.Count == 0) ? bbox.DetectionLabel + " " + ReformatFloatToTwoDecimalPlacesAndEpsilon(bbox.Confidence) : bbox.Classifications[0].Key + " " + ReformatFloatToTwoDecimalPlacesAndEpsilon(bbox.Classifications[0].Value) + "(" + ReformatFloatToTwoDecimalPlacesAndEpsilon(bbox.Confidence) + ")"; string bboxTextBlock = String.Empty; if (bbox.Classifications.Count > 0) { foreach (KeyValuePair <string, string> classification in bbox.Classifications) { bboxTextBlock += classification.Key + " " + ReformatFloatToTwoDecimalPlacesAndEpsilon(classification.Value) + Environment.NewLine; } bboxTextBlock = bboxTextBlock.Trim('\r', '\n'); } // Add information to each bounding box using a tooltip or a splitbutton if (Util.GlobalReferences.TimelapseState.BoundingBoxAnnotate == false) { // Use a tooltip rect.ToolTip = (bbox.Classifications.Count == 0) ? bboxLabel : bboxTextBlock; } else { // Use a split button. The button contains the category label, while its dropdown contains a text list of all predicted categories if (bbox.Classifications.Count <= 1) { Label classificationUIObject = new Label { Opacity = 0.6, Content = bboxLabel, FontSize = 12, Visibility = Visibility.Visible, Background = Brushes.White, Width = Double.NaN, Height = 20, //Double.NaN, Foreground = Brushes.Black, HorizontalAlignment = HorizontalAlignment.Left, Padding = new Thickness(0, -2, 0, -2), VerticalAlignment = VerticalAlignment.Center }; double leftPosition = (screenPositionTopLeft.X - stroke_thickness) < 0 ? 0 : screenPositionTopLeft.X - stroke_thickness; double topPosition = (screenPositionTopLeft.Y - stroke_thickness - 20) < 0 ? 0 : screenPositionTopLeft.Y - stroke_thickness - 20; //Canvas.SetLeft(classificationUIObject, screenPositionTopLeft.X - stroke_thickness); Canvas.SetLeft(classificationUIObject, leftPosition); Canvas.SetTop(classificationUIObject, topPosition); canvas.Children.Add(classificationUIObject); } else { SplitButton classificationUIObject = new SplitButton { Width = Double.NaN, Content = bboxLabel, Opacity = 0.6, FontSize = 12, Background = Brushes.White, Foreground = Brushes.Black, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center, DropDownContent = new TextBlock { Opacity = 0.6, Background = Brushes.White, Foreground = Brushes.Black, FontSize = 12, Text = bboxTextBlock, }, }; // classificationUIObject.SelectionChanged += this.ClassificationUIObject_SelectionChanged; double leftPosition = (screenPositionTopLeft.X - stroke_thickness) < 0 ? 0 : screenPositionTopLeft.X - stroke_thickness; // Canvas.SetLeft(classificationUIObject, screenPositionTopLeft.X - stroke_thickness); double topPosition = (screenPositionTopLeft.Y - stroke_thickness - 20) < 0 ? 0 : screenPositionTopLeft.Y - stroke_thickness - 20; Canvas.SetLeft(classificationUIObject, leftPosition); Canvas.SetTop(classificationUIObject, topPosition); canvas.Children.Add(classificationUIObject); Canvas.SetZIndex(classificationUIObject, 1); } } } Canvas.SetZIndex(canvas, 1); return(true); }
public static void BreakGroup(SchemaView view) { Canvas parent = (Canvas)view.MainPanel; Viewbox g = view.SelectionManager.SelectedObjects[0] as Viewbox; try { Canvas gc = (Canvas)g.Child; while (gc.Children.Count > 0) { System.Windows.FrameworkElement child = gc.Children[0] as System.Windows.FrameworkElement; //this code need for ungrouping not stretched shapes child.SetValue(System.Windows.Controls.Panel.MarginProperty, System.Windows.DependencyProperty.UnsetValue); //Rect b=VisualTreeHelper.GetContentBounds(child); Rect b = VisualTreeHelper.GetDescendantBounds(child); double left = Canvas.GetLeft(child); double top = Canvas.GetTop(child); left = double.IsNaN(left) ? 0 : left; top = double.IsNaN(top) ? 0 : top; if ((child is Shape) && child.ReadLocalValue(System.Windows.Shapes.Shape.StretchProperty).Equals(System.Windows.DependencyProperty.UnsetValue)) { child.Width = b.Width; child.Height = b.Height; Canvas.SetLeft(child, left + b.X); Canvas.SetTop(child, top + b.Y); child.SetValue(System.Windows.Shapes.Shape.StretchProperty, System.Windows.Media.Stretch.Fill); gc.UpdateLayout(); } // excluding rotate from common matrix // need to separate scale*skew matrix on scale and transform transformations Matrix matrGtr = ((Transform)child.TransformToVisual(parent)).Value; double x = matrGtr.OffsetX; double y = matrGtr.OffsetY; double angleY = Math.Atan(matrGtr.M12 / matrGtr.M11) * 180 / Math.PI; matrGtr.OffsetY = 0; matrGtr.OffsetX = 0; RotateTransform rt = new RotateTransform(angleY); matrGtr.Rotate(-angleY); TransformGroup gtr = new TransformGroup(); gtr.Children.Add(new MatrixTransform(matrGtr)); gtr.Children.Add(rt); child.RenderTransform = gtr; child.RenderTransformOrigin = new Point(0.5, 0.5); Point pO = new Point(child.Width * child.RenderTransformOrigin.X, child.Height * child.RenderTransformOrigin.Y); Point p = gtr.Transform(pO); Canvas.SetLeft(child, x - (pO - p).X); Canvas.SetTop(child, y - (pO - p).Y); gc.Children.Remove(child); parent.Children.Add(child); //tool.NotifyObjectCreated(child); } g.Child = null; //tool.NotifyObjectDeleted(g); parent.Children.Remove(g); view.SelectionManager.SelectObject(null); } catch (Exception) { } }
private void Redraw() { TranslateTransform tt = new TranslateTransform(-canvasPos.Left, -canvasPos.Top); ScaleTransform st = new ScaleTransform(canvasSize.Y * zoom, canvasSize.Y * zoom); TransformGroup tg = new TransformGroup() { Children = new TransformCollection() { tt, st } }; List <Shape> shapes = new List <Shape>(); List <Polyline> selections = new List <Polyline>(); HashSet <string> addedNodes = new HashSet <string>(); canvas.Children.Clear(); foreach (KeyValuePair <string, Node> kvp in nodes) { Node node = kvp.Value; Rect aabb = node.AABB; if (!aabb.IntersectsWith(canvasPos)) { continue; } Shape s = node.Draw(); TransformCollection tc = ((TransformGroup)s.RenderTransform).Children; tc.Add(tt); tc.Add(st); shapes.Add(s); addedNodes.Add(kvp.Key); if (node.Selected) { Polyline p = new Polyline() { Stroke = Brushes.Red, StrokeThickness = 2, Points = new PointCollection() { tg.Transform(aabb.TopLeft), tg.Transform(aabb.TopRight), tg.Transform(aabb.BottomRight), tg.Transform(aabb.BottomLeft), tg.Transform(aabb.TopLeft) } }; selections.Add(p); } if (!showRefs[node.Instance.Class]) { continue; } Point p1 = tg.Transform(new Point(node.X, node.Y)); foreach (string target in node.OutReferences) { Node targetNode; if (addedNodes.Contains(target) || !nodes.TryGetValue(target, out targetNode) || !showRefs[targetNode.Instance.Class]) { continue; } Point p2 = tg.Transform(new Point(targetNode.X, targetNode.Y)); Line line = new Line() { Stroke = Brushes.Black, StrokeThickness = 2, X1 = p1.X, Y1 = p1.Y, X2 = p2.X, Y2 = p2.Y }; canvas.Children.Add(line); } foreach (string target in node.InReferences) { Node targetNode; if (addedNodes.Contains(target) || !nodes.TryGetValue(target, out targetNode) || !showRefs[targetNode.Instance.Class]) { continue; } Point p2 = tg.Transform(new Point(targetNode.X, targetNode.Y)); Line line = new Line() { Stroke = Brushes.Black, StrokeThickness = 2, X1 = p1.X, Y1 = p1.Y, X2 = p2.X, Y2 = p2.Y }; canvas.Children.Add(line); } } foreach (Shape shape in shapes) { canvas.Children.Add(shape); } foreach (Polyline p in selections) { canvas.Children.Add(p); } }
public bool RotateFrameKeepSize(double rotationDegrees, BitmapScalingMode scalingMode = BitmapScalingMode.NearestNeighbor) { var clipped = false; var rotationRad = rotationDegrees / 180.0 * Math.PI; var frame = this.BitmapFrame; var w = frame.PixelWidth; var h = frame.PixelHeight; var imageRect = FindNonTransparentRect(frame); var newW = (int)(Math.Abs(imageRect.Width * Math.Sin(rotationRad)) + Math.Abs(imageRect.Height * Math.Cos(rotationRad))); var newH = (int)(Math.Abs(imageRect.Width * Math.Cos(rotationRad)) + Math.Abs(imageRect.Height * Math.Sin(rotationRad))); if (newW > w || newH > h) { clipped = true; } var transformGroup = new TransformGroup(); var rotation = new RotateTransform(rotationDegrees); rotation.CenterX = w / 2.0; rotation.CenterY = h / 2.0; var translate = new TranslateTransform((w - imageRect.Width) / 2.0 - imageRect.X, (h - imageRect.Height) / 2.0 - imageRect.Y); transformGroup.Children.Add(translate); transformGroup.Children.Add(rotation); var origHotspot = new Point(this.HLeft, this.HTop); var transformedHotspot = transformGroup.Transform(origHotspot); var image = new Image() { Source = frame, RenderTransform = transformGroup, Width = w, Height = h, Stretch = Stretch.None, UseLayoutRounding = false, SnapsToDevicePixels = false, }; RenderOptions.SetBitmapScalingMode(image, scalingMode); image.Arrange(new Rect(0, 0, w, h)); var newRect = new Rect(0, 0, w, h); var dv = new DrawingVisual(); using (var ctx = dv.RenderOpen()) { var vb = new VisualBrush(image); vb.TileMode = TileMode.None; vb.ViewboxUnits = BrushMappingMode.Absolute; vb.Viewbox = newRect; ctx.DrawRectangle(vb, null, newRect); } var resultSource = new RenderTargetBitmap(w, h, 96, 96, PixelFormats.Pbgra32); resultSource.Render(dv); this.HLeft = (ushort)transformedHotspot.X; this.HTop = (ushort)transformedHotspot.Y; this.Width = (byte)newW; this.Height = (byte)newH; this._BitmapFrame = BitmapFrame.Create(resultSource); this._PngFile = null; return(clipped); }