Polygon envelopeToPolygon(Envelope env)
 {
     PointCollection points = new PointCollection();
     points.Add(new MapPoint(env.XMin, env.YMin, env.SpatialReference));
     points.Add(new MapPoint(env.XMin, env.YMax, env.SpatialReference));
     points.Add(new MapPoint(env.XMax, env.YMax, env.SpatialReference));
     points.Add(new MapPoint(env.XMax, env.YMin, env.SpatialReference));
     points.Add(new MapPoint(env.XMin, env.YMin, env.SpatialReference));
     Polygon polygon = new Polygon();
     polygon.Rings.Add(points);
     return polygon;
 }
		// Creates a polyline with two paths in the shape of an 'X' centered at the given point
		private Polyline CreatePolylineX(MapPoint center, double length)
		{
			var halfLen = length / 2.0;

			PointCollection coords1 = new PointCollection();
			coords1.Add(new MapPoint(center.X - halfLen, center.Y + halfLen));
			coords1.Add(new MapPoint(center.X + halfLen, center.Y - halfLen));

			PointCollection coords2 = new PointCollection();
			coords2.Add(new MapPoint(center.X + halfLen, center.Y + halfLen));
			coords2.Add(new MapPoint(center.X - halfLen, center.Y - halfLen));

			return new Polyline(new List<PointCollection> { coords1, coords2 }, MyMapView.SpatialReference);
		}
        private static Polygon MultiPolygonWktToPolygon(string wkt)
        {
            var polygon = new Polygon();

            var pointCollection = new PointCollection();
            var removed = wkt.Replace("MULTIPOLYGON (", "");
            var preSplit = removed.Replace(")), ((", "|");
            var rings = preSplit.Split('|');

            foreach (var r in rings)
            {
                PointCollection pc = new PointCollection();

                var r1 = r.Replace("(", "");
                var r2 = r1.Replace(")", "");
                var r3 = r2.Trim();

                var coords = r3.Split(',');
                foreach(var coord in coords)
                {
                    coord.Trim();
                    var xy = coord.Trim().Split(' ');
                    if (xy.Length != 2)
                    continue;

                    pc.Add(new MapPoint(double.Parse(xy[0], CultureInfo.InvariantCulture), double.Parse(xy[1], CultureInfo.InvariantCulture)));
                }

                polygon.Rings.Add(pc);
            }

            return polygon;
        }
        public void OnPointerPressed(InqCanvas inqCanvas, PointerRoutedEventArgs e)
        {
            Debug.WriteLine(e.Pointer.PointerDeviceType);
            _currentStroke = new PointCollection();
            _polyline = new Polyline
            {
                Stroke = new SolidColorBrush(StrokeColor),
                StrokeThickness = 3,
                StrokeLineJoin = PenLineJoin.Round
            };
            inqCanvas.Children.Add(_polyline);

            _polyline.Points = _currentStroke;

            var point = e.GetCurrentPoint(inqCanvas);

            _strokeBuilder.BeginStroke(point);
            _currentStroke.Add(point.Position);

            //_inkManager.

            /*
            //TODO: add data binding for thickness and color
            _currentStroke.StrokeThickness = Math.Max(4.0 * e.GetCurrentPoint(inqCanvas).Properties.Pressure, 2);
            _currentInqLineView.StrokeThickness = _currentStroke.StrokeThickness;
            inqCanvas.Children.Add(_currentInqLineView);
            var currentPoint = e.GetCurrentPoint(inqCanvas);
            _currentStroke.AddPoint(new Point(currentPoint.Position.X, currentPoint.Position.Y));
            */
        }
 /// <summary>
 /// Updates the Shape for the series.
 /// </summary>
 /// <param name="definitionPoints">Locations of the points of each SeriesDefinition in the series.</param>
 protected override void UpdateShape(IList<IEnumerable<Point>> definitionPoints)
 {
     for (int i = SeriesDefinitions.Count - 1; 0 < i; i--)
     {
         PointCollection pointCollection = new PointCollection();
         IEnumerable<Point> topPoints = (ActualIndependentAxis is ICategoryAxis) ? definitionPoints[i].OrderBy(p => p.X) : definitionPoints[i];
         foreach (Point p in topPoints)
         {
             pointCollection.Add(p);
         }
         IEnumerable<Point> bottomPoints = (ActualIndependentAxis is ICategoryAxis) ? definitionPoints[i - 1].OrderByDescending(p => p.X) : definitionPoints[i - 1].Reverse();
         foreach (Point p in bottomPoints)
         {
             pointCollection.Add(p);
         }
         SetPolygonPointsProperty((Polygon)SeriesDefinitionShapes[SeriesDefinitions[i]], pointCollection);
     }
     if (1 <= SeriesDefinitions.Count)
     {
         double plotAreaMaximumDependentCoordinate = ActualDependentAxis.GetPlotAreaCoordinate(ActualDependentRangeAxis.Range.Maximum).Value;
         IComparable zeroValue = ActualDependentRangeAxis.Origin ?? 0.0;
         if (zeroValue.CompareTo(ActualDependentRangeAxis.Range.Minimum) < 0)
         {
             zeroValue = ActualDependentRangeAxis.Range.Minimum;
         }
         if (0 < zeroValue.CompareTo(ActualDependentRangeAxis.Range.Maximum))
         {
             zeroValue = ActualDependentRangeAxis.Range.Maximum;
         }
         double zeroCoordinate = ActualDependentAxis.GetPlotAreaCoordinate(zeroValue).Value;
         PointCollection pointCollection = new PointCollection();
         Point[] topPoints = ((ActualIndependentAxis is ICategoryAxis) ? definitionPoints[0].OrderBy(p => p.X) : definitionPoints[0]).ToArray();
         foreach (Point p in topPoints)
         {
             pointCollection.Add(p);
         }
         if (0 < topPoints.Length)
         {
             Point firstPoint = topPoints[0];
             Point lastPoint = topPoints[topPoints.Length - 1];
             pointCollection.Add(new Point(lastPoint.X, plotAreaMaximumDependentCoordinate - zeroCoordinate));
             pointCollection.Add(new Point(firstPoint.X, plotAreaMaximumDependentCoordinate - zeroCoordinate));
         }
         SetPolygonPointsProperty((Polygon)SeriesDefinitionShapes[SeriesDefinitions[0]], pointCollection);
     }
 }
		// Helper method
		private static PointCollection FromArray(params double[] parameters)
		{
			PointCollection coll = new PointCollection();
			for (int i = 0; i < parameters.Length - 1; i+=2)
			{
				coll.Add(new MapPoint(parameters[i], parameters[i + 1]));
			}
			return coll;
		}
 /// <summary>
 /// Convert a collection of points into a <see cref="PointCollectionList"/> that can be used as paths in <see cref="Polyline"/> types
 /// or rings in <see cref="Polygon"/> types
 /// </summary>
 /// <param name="points"></param>
 /// <returns></returns>
 public static PointCollectionList ToPointCollectionList(this IEnumerable<Point> points)
 {
     var result = new PointCollectionList();
     var pointCollection = new PointCollection();
     foreach (var point in points)
         pointCollection.Add(point.ToPointCollectionEntry());
     result.Add(pointCollection);
     return result;
 }
		// Helper method
		private static PointCollection FromArray(params double[] parameters)
		{
			PointCollection coll = new PointCollection(SpatialReferences.Wgs84);
			var mapPointBuilder = new MapPointBuilder(SpatialReferences.Wgs84);
			for (int i = 0; i < parameters.Length - 1; i+=2)
			{
				mapPointBuilder.SetValues(parameters[i], parameters[i + 1]);
				coll.Add(mapPointBuilder.ToGeometry());
			}
			return coll;
		}
 /// <summary>
 /// Updates the shape for the series.
 /// </summary>
 /// <param name="definitionPoints">Locations of the points of each SeriesDefinition in the series.</param>
 protected override void UpdateShape(IList<IEnumerable<Point>> definitionPoints)
 {
     for (int i = 0; i < SeriesDefinitions.Count; i++)
     {
         PointCollection pointCollection = new PointCollection();
         foreach (Point p in ((ActualIndependentAxis is ICategoryAxis) ? definitionPoints[i].OrderBy(p => p.X) : definitionPoints[i]))
         {
             pointCollection.Add(p);
         }
         SetPolylinePointsProperty((Polyline)SeriesDefinitionShapes[SeriesDefinitions[i]], pointCollection);
     }
 }
        // Creates a square polygon with a hole centered at the given point
        private Polygon CreatePolygonBox(MapPoint center, double length)
        {
            var halfLen = length / 2.0;

            PointCollection coords = new PointCollection();
			coords.Add(new MapPoint(center.X - halfLen, center.Y + halfLen));
			coords.Add(new MapPoint(center.X + halfLen, center.Y + halfLen));
			coords.Add(new MapPoint(center.X + halfLen, center.Y - halfLen));
			coords.Add(new MapPoint(center.X - halfLen, center.Y - halfLen));
			coords.Add(new MapPoint(center.X - halfLen, center.Y + halfLen));

            halfLen /= 3;
            PointCollection coordsHole = new PointCollection();
			coordsHole.Add(new MapPoint(center.X - halfLen, center.Y + halfLen));
			coordsHole.Add(new MapPoint(center.X - halfLen, center.Y - halfLen));
			coordsHole.Add(new MapPoint(center.X + halfLen, center.Y - halfLen));
			coordsHole.Add(new MapPoint(center.X + halfLen, center.Y + halfLen));
			coordsHole.Add(new MapPoint(center.X - halfLen, center.Y + halfLen));

            return new Polygon(
				new List<PointCollection> { coords, coordsHole }, 
				MyMapView.SpatialReference);
        }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            double valueAsDouble = DebugHelper.CastAndAssert<double>(value);

            double LeftBase = 20;

            double RightBase = 20;

            if (BaseShape == null)
            {
                BaseShape = new Polygon();

                BaseShape.Points.Add(new Point(-20,25));
                BaseShape.Points.Add(new Point(-20,20));
                BaseShape.Points.Add(new Point(0,0));
                BaseShape.Points.Add(new Point(20,20));
                BaseShape.Points.Add(new Point(20,25));
            }

            PointCollection newShape = new PointCollection();

            double maxValue = Windows.UI.Xaml.Window.Current.Bounds.Width;

            if (BaseShape != null)
            {
                foreach (Point j in BaseShape.Points)
                {
                    double shiftX = j.X;

                    if (valueAsDouble < LeftBase)
                    {
                        if (j.X < 0)
                        {
                            shiftX = j.X * valueAsDouble / LeftBase;
                        }
                    }
                    if ((maxValue - valueAsDouble) < RightBase)
                    {
                        if (j.X > 0)
                        {
                            shiftX = j.X * (maxValue - valueAsDouble) / RightBase;
                        }
                    }

                    newShape.Add(new Point(shiftX, j.Y));
                }
            }

            return newShape;
        }
        public static Polygon GetRadiusAsPolygonGeodesic(MapPoint center, double distance, int pointCount)
        {
            Polyline line = GetRadiusGeodesicAsPolyline(center, distance, pointCount);
            Polygon poly = new Polygon() { SpatialReference = new SpatialReference(4326) };

            if (line.Paths.Count > 1)
            {
                PointCollection ring = line.Paths[0];
                MapPoint last = ring[ring.Count - 1];
                for (int i = 1; i < line.Paths.Count; i++)
                {
                    PointCollection pnts = line.Paths[i];
                    ring.Add(new MapPoint(180 * Math.Sign(last.X), 90 * Math.Sign(center.Y)));
                    last = pnts[0];
                    ring.Add(new MapPoint(180 * Math.Sign(last.X), 90 * Math.Sign(center.Y)));
                    foreach (MapPoint p in pnts)
                        ring.Add(p);
                    last = pnts[pnts.Count - 1];
                }
                poly.Rings.Add(ring);
            }
            else
            {
                poly.Rings.Add(line.Paths[0]);
            }
            if (distance > _EARTHCIRCUMFERENCE_ * Math.PI / 2 && line.Paths.Count != 2)
            {
                PointCollection pnts = new PointCollection();
                pnts.Add(new MapPoint(-180, -90));
                pnts.Add(new MapPoint(180, -90));
                pnts.Add(new MapPoint(180, 90));
                pnts.Add(new MapPoint(-180, 90));
                pnts.Add(new MapPoint(-180, -90));
                poly.Rings.Add(pnts); //Exterior
            }
            return poly;
        }
        public static Geometry EnvelopeToPolygon(Geometry geometry)
        {
            if (!(geometry is Envelope))
            return null;

              Envelope envelope = geometry as Envelope;
              Polygon polygon = new Polygon();
              polygon.SpatialReference = envelope.SpatialReference;

              PointCollection pointCollection = new PointCollection();

              MapPoint topLeft = new MapPoint();
              topLeft.X = envelope.XMin;
              topLeft.Y = envelope.YMax;
              pointCollection.Add(topLeft);

              MapPoint topRight = new MapPoint();
              topRight.X = envelope.XMax;
              topRight.Y = envelope.YMax;
              pointCollection.Add(topRight);

              MapPoint bottomRight = new MapPoint();
              bottomRight.X = envelope.XMax;
              bottomRight.Y = envelope.YMin;
              pointCollection.Add(bottomRight);

              MapPoint bottomLeft = new MapPoint();
              bottomLeft.X = envelope.XMin;
              bottomLeft.Y = envelope.YMin;
              pointCollection.Add(bottomLeft);

              pointCollection.Add(topLeft);

              polygon.Rings.Add(pointCollection);

              return polygon as Geometry;
        }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var sw = Window.Current.Bounds.Width;
            var sh = Window.Current.Bounds.Height;
            var input = (PointCollection) value;

            var pc = new PointCollection();
            foreach (var p in input)
            {
                pc.Add(new Point(p.X * sw * 0.08, p.Y * sh * 0.08));

            }

            return pc;
        }
Exemple #15
0
 private PointCollection CalculateWheels(WheelsData CurrentData, 
                                         double inc)
 {
     PointCollection pts = new PointCollection();
     var maxAngle = CurrentData.SuggestedMaxTurns * 2 * Math.PI; 
     for (double t = 0; t < maxAngle; t += inc)
     {
         Complex c = new Complex();
         foreach (WheelStageData sd in CurrentData.Stages)
         {
             c += sd.Amplitude * Complex.Exp(new Complex(0,sd.Frequency * t ));
         }
         pts.Add(new Point(c.Real, c.Imaginary));
     }
     return pts;
 }
        private void AjaxReport01()
        {
            // hcVendas.Appearance = new Appearance { renderTo = "container", zoomType = "x" };
               // hcVendas.YAxis.Add(new YAxisItem { title = new Title("SoC"), type = AxisDataType.linear });
            //hcVendas.XAxis.Add(new XAxisItem { maxZoom = 5, labels = (new Labels { rotation = 45, step = 2 }) });

            hcVendas.Title = new Title("SoC Daily");
            hcVendas.SubTitle = new SubTitle("Min - Max - Dash");

            hcVendas.Theme = "gray";
            hcVendas.Legend = new Legend { align = Align.right, layout = Layout.vertical, verticalAlign = VerticalAlign.top, x = -10, y = 70, borderWidth = 0 };
               hcVendas.Appearance = new Appearance { renderTo = "container", animation=false};
               hcVendas.YAxis.Add(new YAxisItem {title = new Title("SoC %")});
             //  hcVendas.XAxis.Add(new XAxisItem { title = new Title("Time in Hours") });
               hcVendas.XAxis.Add(new XAxisItem { type = AxisDataType.datetime, dateTimeLabelFormats = new DateTimeLabelFormats { hour = "%H" }, title = new Title("Time in Hours") });
              // hcVendas.XAxis.Add(new XAxisItem { categories = new object[] { "1:00", "2:00", "3:00", "4:00", "5:00", "6:00", "7:00", "8:00", "9:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00", "24:00"} });

              // hcVendas.Tooltip = new ToolTip("Highcharts.dateFormat("%H:%M", this.x) +": "+ this.y");

            //Get point collection
            var pointCollectionSocMin = new PointCollection();
            var pointCollectionSocMax = new PointCollection();
            var pointCollectionSocDas = new PointCollection();
            GetChartData gd = new GetChartData();

             DateTime dt1 = new DateTime(2015,8,22);

             DataTable dataTable = gd.GetSoCDt(194, dt1);
            foreach (DataRow row in dataTable.Rows)
            {
                pointCollectionSocMin.Add(new Point(Convert.ToInt64((DateTime.Parse(row["Time_Occur"].ToString()).Subtract(new DateTime(2015, 1, 1))).TotalMilliseconds), Convert.ToDouble(row["SocMin"])));
                pointCollectionSocMax.Add(new Point(Convert.ToInt64((DateTime.Parse(row["Time_Occur"].ToString()).Subtract(new DateTime(2015, 1, 1))).TotalMilliseconds), Convert.ToDouble(row["SocMax"])));
                pointCollectionSocDas.Add(new Point(Convert.ToInt64((DateTime.Parse(row["Time_Occur"].ToString()).Subtract(new DateTime(2015, 1, 1))).TotalMilliseconds), Convert.ToDouble(row["SocDash"])));
               // pointCollection.Add(new Point(DateTime.Parse(row["Time_Occur"].ToString()), Convert.ToDouble(row["SocMin"])));
            }

            //Add data to serie
            var series = new Collection<Serie> { new Serie { name = "SocMin", data = pointCollectionSocMin.ToArray() }, new Serie { name = "SocMax", data = pointCollectionSocMax.ToArray() }, new Serie { name = "SocDash",  data = pointCollectionSocDas.ToArray() } };
            hcVendas.PlotOptions = new PlotOptionsLine {marker= new Marker{enabled=false}, dataLabels = new DataLabels { enabled = false }};

            //Bind the control
            hcVendas.DataSource = series;
            hcVendas.DataBind();
        }
        private static Polygon SinglePolygonWktToPolygon(string wkt)
        {
            var polygon = new Polygon();
            var pointCollection = new PointCollection();
            var removed = wkt.Replace("POLYGON ((", "").Replace("))", "");
            var coords = removed.Split(',');

            foreach (var coord in coords)
            {
                var xy = coord.TrimStart().Split(' ');
                if (xy.Length != 2)
                    continue;

                pointCollection.Add(new MapPoint(double.Parse(xy[0], CultureInfo.InvariantCulture), double.Parse(xy[1], CultureInfo.InvariantCulture)));
            }

            polygon.Rings.Add(pointCollection);

            return polygon;
        }
        public static List <Polygon> DrawMapByCoordinates(JArray coordinates)
        {
            List <Polygon> polygons = new List <Polygon>();

            if (coordinates.Count == 1)
            {
                PointCollection points  = new PointCollection();
                Polygon         polygon = new Polygon();
                for (int j = 0; j < coordinates[0].Count(); j++)
                {
                    //polygon.Points.Add(new Point(Double.Parse(coordinates[0][j][0].ToString()), -Double.Parse(coordinates[0][j][1].ToString())));
                    points.Add(new Point(Double.Parse(coordinates[0][j][0].ToString()) * 9 + 1400,
                                         -Double.Parse(coordinates[0][j][1].ToString()) * 9 + 700));
                }
                polygon.Points = points;
                polygons.Add(polygon);
            }
            else
            {
                for (int i = 0; i < coordinates.Count; i++)
                {
                    PointCollection points  = new PointCollection();
                    Polygon         polygon = new Polygon();
                    for (int k = 0; k < coordinates[i][0].Count(); k++)
                    {
                        //polygon.Points.Add(
                        //    new Point(Double.Parse(coordinates[i][0][k][0].ToString()), -Double.Parse(coordinates[i][0][k][1].ToString())));
                        points.Add(
                            new Point(Double.Parse(coordinates[i][0][k][0].ToString()) * 9 + 1400,
                                      -Double.Parse(coordinates[i][0][k][1].ToString()) * 9 + 700));
                    }
                    polygon.Points = points;
                    polygons.Add(polygon);
                }
            }
            return(polygons);
        }
Exemple #19
0
        /// <summary>
        /// Toggles the start side of a polygon.
        /// </summary>
        public void ToggleStartSide()
        {
            // Get first view model point
            PolygonPointViewModel point1 = PointCollection[0];

            // Remove the first view model point
            PointCollection.Remove(point1);

            // Add the point to the end of the point collection
            PointCollection.Add(point1);

            // Get the first model point
            PolygonPoint pt1 = Ellipse.Points[0];

            // Remove the first model point
            Ellipse.Points.Remove(pt1);

            // Add the point to the end of the point collection
            Ellipse.Points.Add(pt1);

            // Increment the start side
            Ellipse.StartSideRotation++;

            // If we are past the last side then...
            if (Ellipse.StartSideRotation > 3)
            {
                // Wrap around to the first side
                Ellipse.StartSideRotation = 0;
            }

            // Update the green line segment
            Segments[0]       = new LineSegmentViewModel(PointCollection[0], PointCollection[1]);
            Segments[0].Color = Colors.Lime;

            // Force the view converters to run
            NotifyPointCollectionChanged();
        }
Exemple #20
0
 private void Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
 {
     if (addingPoints)
     {
         double x = e.GetPosition(this).X, y = e.GetPosition(this).Y;
         points.Add(new Point(x, y));
         Ellipse ellipse = new Ellipse()
         {
             Fill            = Brushes.LightGray,
             StrokeThickness = 1,
             Stroke          = Brushes.Gray,
             Width           = 12,
             Height          = 12
         };
         Canvas.SetLeft(ellipse, x - ellipse.Width / 2);
         Canvas.SetTop(ellipse, y - ellipse.Height / 2);
         canvas.Children.Add(ellipse);
         ellipses.Add(ellipse);
     }
     else if (mMove)
     {
         FirstPoint.Content = FirstPoint.Content = latMousePoints[0].X.ToString() + ", " + latMousePoints[0].Y.ToString();
         firstPoint         = latMousePoints.First();
         MoveShape(e.GetPosition(this).X - firstPoint.X, e.GetPosition(this).Y - firstPoint.Y);
         latMousePoints.Clear();
     }
     else if (mRotate)
     {
         //p1 p2 p3
         // p1 - punkt pligonu, p2 - tam ghdzie klika myuszka, p3 - tam gdzie puszcza myszka
         FirstPoint.Content = FirstPoint.Content = latMousePoints[0].X.ToString() + ", " + latMousePoints[0].Y.ToString();
         firstPoint         = latMousePoints.First();
         double alfa = Math.Acos((Math.Pow(GetDistance(points[0], firstPoint), 2) + Math.Pow(GetDistance(points[0], e.GetPosition(this)), 2) - Math.Pow(GetDistance(firstPoint, e.GetPosition(this)), 2)) / (2 * GetDistance(points[0], firstPoint) * GetDistance(points[0], e.GetPosition(this))));
         RotateShape(e.GetPosition(this).X - firstPoint.X, e.GetPosition(this).Y - firstPoint.Y, alfa);
         latMousePoints.Clear();
     }
 }
Exemple #21
0
        public Point GetMousePositionWindowsForms()
        {
            Point point = Mouse.GetPosition(canvas);
            bool  added = false;

            if (point.X > 0 && point.Y > 0)
            {
                Text(point.X, point.Y, "(" + (point.X - 125) + ":" + (-(point.Y - 125)) + ")", Colors.Red);
                myPointCollection.Add(point);
                added = true;
            }

            if (buttonsDisplay.Children.Count < 10 && added)
            {
                Button b = new Button();
                b.Click  += new RoutedEventHandler(this.button_Click);
                b.Content = "Change";
                b.Name    = "Button" + myPointCollection.IndexOf(point).ToString();

                buttonsDisplay.Children.Add(b);

                TextBox tx = new TextBox();
                tx.Name      = "X" + myPointCollection.IndexOf(point).ToString();
                tx.Text      = (point.X - 125).ToString();
                tx.MaxLength = 4;
                tx.MaxLines  = 1;
                xDisplay.Children.Add(tx);

                TextBox ty = new TextBox();
                ty.Name      = "Y" + myPointCollection.IndexOf(point).ToString();
                ty.Text      = (-(point.Y - 125)).ToString();
                ty.MaxLength = 4;
                ty.MaxLines  = 1;
                yDisplay.Children.Add(ty);
            }
            return(new Point(point.X, point.Y));
        }
Exemple #22
0
        private void m_mousedown(object sender, MouseEventArgs e)
        {
            if (!istouch)
            {
                this.ismouse = true;
                if (ismouse)
                {
                    if (m_textbox != null)
                    {
                        m_textbox.Text += "mousedown" + (e.GetPosition(this.m_canvas).ToString()) + "\n";
                    }

                    if (!this.sketching)
                    {
                        Polyline curvePolyline = new Polyline();
                        if (this.type == PenType.Pen)
                        {
                            curvePolyline.Stroke          = Brushes.White;
                            curvePolyline.StrokeThickness = 2;
                        }
                        else
                        {
                            curvePolyline.Stroke          = m_canvas.Background;
                            curvePolyline.StrokeThickness = this.erasesize;
                        }

                        curvePolyline.StrokeLineJoin = PenLineJoin.Round;
                        var Points = new PointCollection();
                        Points.Add(e.GetPosition(this.m_canvas));
                        curvePolyline.Points = Points;
                        strokes_page_all[this.page].polylines.Add(curvePolyline);
                        m_canvas.Children.Add(curvePolyline);
                        this.sketching = true;
                    }
                }
            }
        }
        private void drawTriangle(MouseEventArgs e)
        {
            Geometry.Point center = new Geometry.Point(0, 0);
            Geometry.Point r      = new Geometry.Point(0, 0);

            Polygon tr = new Polygon();

            tr.Stroke = new SolidColorBrush(Color.FromArgb(parameters.LineColor.a,
                                                           parameters.LineColor.r, parameters.LineColor.g,
                                                           parameters.LineColor.b));
            tr.StrokeThickness = parameters.Thickness;

            PointCollection myPointCollection = new PointCollection();

            foreach (var item in new Geometry.Triangle(
                         new Geometry.Point(startPoint.X, startPoint.Y),
                         new Geometry.Point(e.GetPosition(inkPanel).X, e.GetPosition(inkPanel).Y))
                     .Points(parameters))
            {
                myPointCollection.Add(new Point(item.x, item.y));
            }

            tr.Points = myPointCollection;

            if (checkBoxFill.IsChecked == true)
            {
                tr.Fill = new SolidColorBrush(Color.FromArgb(
                                                  parameters.FillColor.a,
                                                  parameters.FillColor.r,
                                                  parameters.FillColor.g,
                                                  parameters.FillColor.b));
            }

            inkPanel.Children.Add(tr);
            currentShape = tr;
        }
Exemple #24
0
        private void btnDrawPoluline_Click(object sender, RoutedEventArgs e)
        {
            //määritellään polyline
            SolidColorBrush scb = new SolidColorBrush();

            scb.Color = Colors.Crimson;
            Polyline pl = new Polyline();

            pl.Stroke          = scb;
            pl.StrokeThickness = 3;
            myGrid.Children.Add(pl); //lisätään polyline-olio gridin lapseksi
            //arvotaan polylinen pisteet
            Random          rnd = new Random();
            PointCollection myPoints = new PointCollection();
            int             x, y;

            for (int i = 0; i < 100; i++)
            {
                x = rnd.Next((int)this.Width);
                y = rnd.Next((int)this.Height);
                myPoints.Add(new Point(x, y));
            }
            pl.Points = myPoints;
        }
Exemple #25
0
        /// <summary> Initializes the user interface for showing the route on screen. </summary>
        /// <param name="route"> The calculated route.</param>
        #region doc:display result
        private void DisplayRouteInMap(Route route)
        {
            ContextMenuService.SetContextMenu(_wpfMap, cm);

            // already disposed
            if (disposed)
            {
                return;
            }

            (routingLayer as ShapeLayer)?.Shapes.Clear();

            if (route == null)
            {
                return;
            }

            var points = new PointCollection();

            foreach (PlainPoint p in route.polygon.lineString.wrappedPoints)
            {
                points.Add(new System.Windows.Point(p.x, p.y));
            }

            new UseCases.RoutePolyline(routingLayer as ShapeLayer)
            {
                Points  = points,
                ToolTip = $"{route.info.distance / 1000.0:0,0.0}km\n{TimeSpan.FromSeconds(route.info.time)}",
                Color   = Colors.Blue
            };

            routingLayer.Refresh();
            wayPointLayer.Refresh();

            ZoomToRoute(route);
        }
Exemple #26
0
        private void PrintOutputGraph_AllOfEach()
        {
            var outputOffset = _trainingDataMeta["OutputOffset"].Value <int>();
            var input        = new PointCollection();
            var output       = new PointCollection();
            var expected     = new PointCollection();
            var sampleCount  = _trainingData["Inputs"].Count;

            for (var i = 0; i < sampleCount; i++)
            {
                var inputSize  = _trainingData["Inputs"][i].Count;
                var outputSize = _trainingData["Outputs"][i].Count;
                for (var j = 0; j < inputSize; ++j)
                {
                    input.Add(new Point(i * inputSize + j, _trainingData["Inputs"][i][j]));
                }

                for (var j = 0; j < inputSize; ++j)
                {
                    output.Add(new Point(i * inputSize + j + outputOffset,
                                         j < outputSize ? _nn.GenerateOutput(_trainingData["Inputs"][i])[j] : 0));
                }

                for (var j = 0; j < inputSize; j++)
                {
                    expected.Add(new Point(i * inputSize + j + outputOffset,
                                           j < outputSize ? _trainingData["Outputs"][i][j] : 0));
                }
            }

            OutputPlot.LineThickness = 2.5;
            OutputPlot.ScaleXAxis    = true;
            OutputPlot.Add("Input", input, Colors.Black);
            OutputPlot.Add("Expected", expected, Colors.White);
            OutputPlot.Add("Output", output, Colors.Purple);
        }
        /// <summary> Shows the calculated route as a RoutePolyline on screen. </summary>
        /// <param name="route">The calculated route.</param>
        private void DisplayRouteInMap(Route route)
        {
            if (route == null)
            {
                return;
            }

            var points = new PointCollection();

            foreach (PlainPoint p in route.polygon.lineString.wrappedPoints)
            {
                points.Add(new System.Windows.Point(p.x, p.y));
            }

            new RoutePolyline(shapeLayer)
            {
                Points  = points,
                ToolTip = $"{route.info.distance / 1000.0:0,0.0}km\n{TimeSpan.FromSeconds(route.info.time)}",
                Color   = (route.dynamicInfo != null) ? Colors.Green : Colors.Gray,
                Width   = (route.dynamicInfo != null) ? 25 : 15
            };

            ZoomToRoute(route);
        }
Exemple #28
0
        private PointCollection StarPoints(int x, int y)
        {
            PointCollection points = new PointCollection();

            double rx = (double)Constants.Modul / 2;
            double ry = (double)Constants.Modul / 2;
            double cx = x + rx;
            double cy = y + ry;

            // Start at the top.
            double theta  = -Math.PI / 2;
            double dtheta = 4 * Math.PI / NumPoints;

            for (int i = 0; i < NumPoints; i++)
            {
                var point = new Point(
                    (float)(cx + rx * Math.Cos(theta)),
                    (float)(cy + ry * Math.Sin(theta)));
                theta += dtheta;
                points.Add(point);
            }

            return(points);
        }
Exemple #29
0
        // HealpixBorderLine for the polar cap area
        private PointCollection HealpixBorderLinePC(short n, short k,
                                                    double interval, double start_phi, double end_phi, bool flag)
        {
            double delta_phi = interval;
            double phi       = start_phi - delta_phi;

            PointCollection P = new PointCollection();

            while (phi < end_phi)
            {
                double theta, dTheta_dPhi;
                HealpixBorderGetNextPC(n, k, phi, delta_phi, flag, out phi, out theta, out dTheta_dPhi);
                P.Add(new Point(theta, phi));
                // distance in the tangent plane on the unit sphere
                double dL_dPhi = Math.Sqrt(dTheta_dPhi * dTheta_dPhi + Math.Pow(Math.Sin(theta), 2));
                // decide the next sampling point so that each distance between the points becomes same
                delta_phi = interval / dL_dPhi;
                if (phi + delta_phi > end_phi)
                {
                    delta_phi = end_phi - phi;  // add the end edge point
                }
            }
            return(P);
        }
        private PointCollection convertirSeñalAGrafica(PointCollection puntosSeñal)
        {
            PointCollection puntosGrafica = new PointCollection();

            double escalaX = scrContenedorGrafica.Width;
            double escalaY = (scrContenedorGrafica.Height - 20) / 2;

            amplitudMaxima = 1;
            foreach (Point punto in puntosSeñal)
            {
                if (punto.Y > amplitudMaxima)
                {
                    amplitudMaxima = punto.Y;
                }
            }
            foreach (Point muestra in puntosSeñal)
            {
                puntosGrafica.Add
                    (new Point(escalaX * (muestra.X - señal.TiempoInicial),
                               -(muestra.Y / amplitudMaxima) * escalaY + escalaY));
            }

            return(puntosGrafica);
        }
Exemple #31
0
        /// <summary>
        /// Create and return a single triangle given the center point, rotation and colour.
        /// </summary>
        /// <param name="center"></param>
        /// <param name="rotation"></param>
        /// <param name="colour"></param>
        /// <returns></returns>
        public static Polygon CreateTriangle(Point center, float rotation, SolidColorBrush colour)
        {
            Polygon triangle = new Polygon();

            triangle.Stroke              = Brushes.Black;
            triangle.Fill                = colour;
            triangle.StrokeThickness     = 2;
            triangle.HorizontalAlignment = HorizontalAlignment.Left;
            triangle.VerticalAlignment   = VerticalAlignment.Top;
            Point[]         originalPoints    = new Point[] { new Point(0, -10), new Point(-6, 10), new Point(6, 10) };
            PointCollection myPointCollection = new PointCollection();

            for (var i = 0; i < 3; ++i)
            {
                Point rotatedPoint = new Point(
                    (originalPoints[i].X * Math.Cos(rotation)) - (originalPoints[i].Y * Math.Sin(rotation)),
                    (originalPoints[i].Y * Math.Cos(rotation)) + (originalPoints[i].X * Math.Sin(rotation))
                    );
                Point finalPoint = new Point(rotatedPoint.X + center.X, rotatedPoint.Y + center.Y);
                myPointCollection.Add(finalPoint);
            }
            triangle.Points = myPointCollection;
            return(triangle);
        }
Exemple #32
0
        /// <summary>
        ///     Перерисовывает плоскость
        /// </summary>
        public void redrawLine()
        {
            if (polygone != null)
            {
                Canvas.Children.Remove(polygone);
            }

            polygone      = new Polygon();
            polygone.Fill = fillingBrush;
            Panel.SetZIndex(polygone, 0);
            var myPointCollection = new PointCollection();

            foreach (var i in dots)
            {
                myPointCollection.Add(i.absoluteCord);
            }

            polygone.Points               = myPointCollection;
            polygone.MouseEnter          += onPolygone;
            polygone.MouseLeave          += NotOnPolygone;
            polygone.MouseLeftButtonDown += ClickOnPolygone;
            polygone.MouseUp             += UpMouse;
            Canvas.Children.Add(polygone);
            if (lines.Count == 0)
            {
                for (var i = 0; i < dots.Count; i++)
                {
                    lines.Add(new MyLine(dots[i], dots[(i + 1) % dots.Count], this, 1, linesBrush));
                }
            }

            foreach (var i in lines)
            {
                i.DrawLine();
            }
        }
Exemple #33
0
        public MainPage()
        {
            this.InitializeComponent();
            Random r = new Random();

            for (int i = 0; i < 3000; i++)
            {
                var   a   = r.Next(100, 200);
                var   b   = r.Next(100, 200);
                Point pnt = new Point(a, b);
                polyLineSegment.Points.Add(pnt);
                pointsCollection.Add(pnt);
            }

            figure.StartPoint = pointsCollection[0];
            figure.Segments.Add(polyLineSegment);
            geometry.Figures.Add(figure);
            polyLineShape.PolyLinePath                 = new Windows.UI.Xaml.Shapes.Path();
            polyLineShape.PolyLinePath.Data            = geometry;
            polyLineShape.PolyLinePath.Stroke          = new SolidColorBrush(Colors.Red);
            polyLineShape.PolyLinePath.StrokeThickness = 3;

            contentControl.Content = polyLineShape.PolyLinePath;
        }
        private void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e)
        {
            try
            {
                // Add the map point to the list that will be used by the GeometryEngine.ConvexHull operation.
                _inputPointCollection.Add(e.Location);

                // Check if there are at least three points.
                if (_inputPointCollection.Count > 2)
                {
                    // Enable the button for creating hulls.
                    _createHullButton.Enabled = true;
                }

                // Create a simple marker symbol to display where the user tapped/clicked on the map. The marker symbol
                // will be a solid, red circle.
                SimpleMarkerSymbol userTappedSimpleMarkerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Circle, System.Drawing.Color.Red, 10);

                // Create a new graphic for the spot where the user clicked on the map using the simple marker symbol.
                Graphic userTappedGraphic = new Graphic(e.Location, userTappedSimpleMarkerSymbol)
                {
                    // Set the Z index for the user tapped graphic so that it appears above the convex hull graphic(s) added later.
                    ZIndex = 1
                };

                // Add the user tapped/clicked map point graphic to the graphic overlay.
                _graphicsOverlay.Graphics.Add(userTappedGraphic);
            }
            catch (Exception ex)
            {
                // Display an error message if there is a problem adding user tapped graphics.
                UIAlertController alertController = UIAlertController.Create("Can't add user-tapped graphic.", ex.Message, UIAlertControllerStyle.Alert);
                alertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(alertController, true, null);
            }
        }
Exemple #35
0
        /// <summary>
        /// Updates data in <see cref="Points"/> and causes a redrawing of line graph.
        /// </summary>
        /// <param name="x">A set of x coordinates of new points.</param>
        /// <param name="y">A set of y coordinates of new points.</param>
        public void Plot(IEnumerable x, IEnumerable y)
        {
            if (x == null)
            {
                throw new ArgumentNullException("x");
            }
            if (y == null)
            {
                throw new ArgumentNullException("y");
            }

            var points = new PointCollection();
            var enx    = x.GetEnumerator();
            var eny    = y.GetEnumerator();

            while (true)
            {
                var nx = enx.MoveNext();
                var ny = eny.MoveNext();
                if (nx && ny)
                {
                    points.Add(new Point(Convert.ToDouble(enx.Current, CultureInfo.InvariantCulture),
                                         Convert.ToDouble(eny.Current, CultureInfo.InvariantCulture)));
                }
                else if (!nx && !ny)
                {
                    break;
                }
                else
                {
                    throw new ArgumentException("x and y have different lengthes");
                }
            }

            Points = points;
        }
Exemple #36
0
        public void FindCoordinates()
        {
            radius = (int)(MainCanvas.ActualHeight * 0.4);

            path = new int[count][];
            Array.Copy(MainWindow.table1.correctedPath, path, count);
            matrixPath = new int[count][];
            Array.Copy(MainWindow.table1.copyMatrix, matrixPath, count);

            int x, y;

            int xCentrе = (int)(MainCanvas.ActualWidth / 2);
            int yCentre = (int)(MainCanvas.ActualHeight / 2);

            for (int i = 0; i < count; i++)
            {
                x = (int)(xCentrе + (radius * Math.Cos(2 * i * Math.PI / count)));
                y = (int)(yCentre + (radius * Math.Sin(2 * i * Math.PI / count)));
                coordinates.Add(new Point(x, y));
                x -= 8;
                y -= 12;
                coordNodeNames.Add(new int[] { x, y });
            }
        }
Exemple #37
0
        private void DrawPolygon_Click(object sender, RoutedEventArgs e)
        {
            Polygon myPolygon = new Polygon
            {
                Stroke              = Brushes.Black,
                Fill                = Brushes.SandyBrown,
                StrokeThickness     = 2,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Center
            };

            PointCollection allPoints = new PointCollection();

            foreach (var item in allPointsList)
            {
                allPoints.Add(item);
            }

            removePolygon.Points = allPoints;

            myPolygon.Points = allPoints;

            myCanvas.Children.Insert(1, myPolygon);
        }
 private void updateGraph(int num)
 {
     this._graphs._graphsHost.Clear();
     try
     {
         PointCollection pntCollection = new PointCollection();
         double          yMax          = double.NegativeInfinity;
         double          yMin          = double.PositiveInfinity;
         double          d             = (this._max - this._min) / num;
         double          t             = 0;
         for (int i = 0; i <= num; i++)
         {
             double x_   = this._min + t;
             double yVal = this.interpolation.Interpolate(x_);
             Point  pnt  = new Point(x_, yVal);
             t += d;
             pntCollection.Add(pnt);
             yMax = (yMax < yVal) ? yVal : yMax;
             yMin = (yMin > yVal) ? yVal : yMin;
         }
         this._graphs._yMax.Text = yMax.ToString();
         this._graphs._yMin.Text = yMin.ToString();
         this._graphs._xMin.Text = this._min.ToString();
         this._graphs._xMax.Text = this._max.ToString();
         if (yMax - yMin < .01)
         {
             this._graphs._graphsHost.Clear();
             throw new ArgumentException(string.Format("f(x) = {0}\n\tWPF Charts does not support drawing it!", ((yMax + yMin) / 2).ToString()));
         }
         this._graphs._graphsHost.AddTrendLine(pntCollection);
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message);
     }
 }
        public async Task<List<PointCollection>> ChangePointToPlaceSymbol()
        {
            YouMapsSymbol currentSymbol = (App.Current as App).CurrentSymbolToBePlaced;
            List<PointCollection> pointsToChange = currentSymbol.SymbolPoints.ToList<PointCollection>();
            double centerX = currentSymbol.HighX - currentSymbol.LowX;
            double centerY = currentSymbol.HighY - currentSymbol.LowY;
            Point centerPoint = new Point{X = centerX, Y = centerY};
            Point topLeft = new Point{X = pointerPressedLocation.X-centerPoint.X, Y = pointerPressedLocation.Y - centerPoint.Y};

            List<PointCollection> changedPoints = new List<PointCollection>();
            foreach(PointCollection pc in pointsToChange)
            {
                PointCollection newPointsCollection = new PointCollection();
                foreach(Point p in pc)
                {
                    Point newPoint = new Point{X = topLeft.X+p.X,Y=topLeft.Y+p.Y};
                    Debug.WriteLine("PointerPressed: " + pointerPressedLocation);
                    Debug.WriteLine("X: " + newPoint.X + " Y: " + newPoint.Y);
                    newPointsCollection.Add(newPoint);
                }
                changedPoints.Add(newPointsCollection);
            }
            return changedPoints;
        }
Exemple #40
0
        public void ZeitverlaufZeichnen(double dt, double tmax, double mY, double[] ordinaten)
        {
            maxY = mY;
            var nSteps      = (int)(tmax / dt) + 1;
            var zeitverlauf = new Polyline
            {
                Stroke          = Red,
                StrokeThickness = 2
            };
            var stützpunkte = new PointCollection();

            for (var i = 0; i < nSteps; i++)
            {
                var point = new Point(dt * i * auflösungH, -ordinaten[i] * auflösungV);
                stützpunkte.Add(point);
            }
            zeitverlauf.Points = stützpunkte;

            // setz oben/links Position zum Zeichnen auf dem Canvas
            SetLeft(zeitverlauf, RandLinks);
            SetTop(zeitverlauf, mY * auflösungV + RandOben);
            // zeichne Shape
            visualErgebnisse.Children.Add(zeitverlauf);
        }
Exemple #41
0
        /// <summary>
        /// Converts a <see cref="ESRI.ArcGIS.Client.Geometry.Polyline"/> to a
        /// <see cref="ESRI.ArcGIS.Client.Geometry.Polygon"/>
        /// </summary>
        internal static Polygon ToPolygon(this Polyline polyline)
        {
            Polygon polygon = new Polygon()
            {
                SpatialReference = polyline.SpatialReference
            };

            foreach (PointCollection path in polyline.Paths)
            {
                // Clone the path to be a ring of the polygon
                PointCollection ring = path.Clone();

                // Close the ring if it is not already
                if (ring[0].X != ring[ring.Count - 1].X ||
                    ring[0].Y != ring[ring.Count - 1].Y)
                {
                    ring.Add(ring[0].Clone());
                }

                // Add the ring to the polygon
                polygon.Rings.Add(ring);
            }
            return(polygon);
        }
Exemple #42
0
        /// <summary>
        ///     Generates texture coordinates as if mesh were a plane.
        ///
        ///     Notes:
        ///         1) v is flipped for you automatically
        ///         2) 'mesh' is not modified. If you want the generated coordinates
        ///            to be assigned to mesh, do:
        ///
        ///            mesh.TextureCoordinates = GeneratePlanarTextureCoordinates(mesh, foo)
        ///
        /// </summary>
        /// <param name="mesh">The mesh</param>
        /// <param name="dir">The normal of the plane</param>
        /// <returns>The generated texture coordinates</returns>
        public static PointCollection GeneratePlanarTextureCoordinates(MeshGeometry3D mesh, Vector3D dir)
        {
            if (mesh == null)
            {
                return(null);
            }

            Rect3D                bounds    = mesh.Bounds;
            int                   count     = mesh.Positions.Count;
            PointCollection       texcoords = new PointCollection(count);
            IEnumerable <Point3D> positions = TransformPoints(ref bounds, mesh.Positions, ref dir);

            foreach (Point3D vertex in positions)
            {
                // The plane is looking along positive Y, so Z is really Y

                texcoords.Add(new Point(
                                  GetPlanarCoordinate(vertex.X, bounds.X, bounds.SizeX),
                                  GetPlanarCoordinate(vertex.Z, bounds.Z, bounds.SizeZ)
                                  ));
            }

            return(texcoords);
        }
Exemple #43
0
        /// <summary>
        /// Adds a (possibly hollow) pipe.
        /// </summary>
        /// <param name="point1">
        /// The start point.
        /// </param>
        /// <param name="point2">
        /// The end point.
        /// </param>
        /// <param name="innerDiameter">
        /// The inner diameter.
        /// </param>
        /// <param name="diameter">
        /// The outer diameter.
        /// </param>
        /// <param name="thetaDiv">
        /// The number of divisions around the pipe.
        /// </param>
        public void AddPipe(Point3D point1, Point3D point2, double innerDiameter, double diameter, int thetaDiv)
        {
            var dir = point2 - point1;

            double height = dir.Length;

            dir.Normalize();

            var pc = new PointCollection
            {
                new Point(0, innerDiameter / 2),
                new Point(0, diameter / 2),
                new Point(height, diameter / 2),
                new Point(height, innerDiameter / 2)
            };

            if (innerDiameter > 0)
            {
                // Add the inner surface
                pc.Add(new Point(0, innerDiameter / 2));
            }

            this.AddRevolvedGeometry(pc, point1, dir, thetaDiv);
        }
Exemple #44
0
        //draw existing lines after window resize
        private void DrawLines(Canvas can, List <double> guesses)
        {
            //Create temporary collection for points after scaling
            var tmpCollection = new PointCollection();

            for (int i = 0; i < iter; i++)
            {
                //set appearance
                Polyline polyline = new Polyline();
                polyline.StrokeThickness = guesses.Count - i;
                polyline.Stroke          = new SolidColorBrush(colors[i]);

                //scale points (world to device) and add them do temporary collection
                foreach (Point p in pointsColection[i])
                {
                    tmpCollection.Add(WtoD(p));
                }
                polyline.Points = tmpCollection;

                //draw on canvas
                can.Children.Add(polyline);
                tmpCollection = new PointCollection();//clear collection for next
            }
        }
 private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
 {
     mousedown = true;
     points    = new PointCollection();
     points.Add(e.GetPosition(canvas));
     polyLine            = new Polyline();
     polyLine.MouseDown += (s, arg) =>
     {
         Polyline line = (Polyline)s;
         if (e.RightButton == MouseButtonState.Pressed && delete)
         {
             canvas.Children.Remove(line);
         }
         else if (e.RightButton == MouseButtonState.Pressed)
         {
             line.Stroke = color;
         }
     };
     polyLine.Stroke          = color;
     polyLine.StrokeThickness = thickness;
     polyLine.Fill            = Brushes.Transparent;
     polyLine.Points          = points;
     canvas.Children.Add(polyLine);
 }
Exemple #46
0
        /// <summary>
        /// Calculates points collection for the middle segment
        /// </summary>
        /// <returns></returns>
        protected PointCollection GetMiddleSegmPoints()
        {
            var x  = XByAngle((VirtualHeight / 2) + HorizSegH / 2) + (VertSegW + GapW);
            var x1 = XByAngle(VirtualHeight / 2) + VertSegBotPartW + GapW;
            var x2 = XByAngle(VirtualHeight / 2 - HorizSegH / 2) + VertSegW + GapW;

            PointCollection points = new PointCollection();

            // three left points, starting from the bottom point
            points.Add(new Point(x, (VirtualHeight / 2) + HorizSegH / 2));
            points.Add(new Point(x1, (VirtualHeight / 2)));
            points.Add(new Point(x2, (VirtualHeight / 2) - HorizSegH / 2));

            // three right points, starting from the top point
            points.Add(new Point(VirtualWidth - x, RightTopSegmPoints[6].Y + GapW / 2));
            points.Add(new Point(VirtualWidth - x1, VirtualHeight / 2));
            points.Add(new Point(VirtualWidth - x2, RightBottomSegmPoints[0].Y - GapW / 2));
            return(points);
        }
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var points = new PointCollection();
            var user   = (Skype4Sharp.User)value;

            if (user.Username == App.mainSkype.selfProfile.Username)
            {
                points.Add(new Point(160, 0));
                points.Add(new Point(180, 0));
                points.Add(new Point(180, 20));
            }
            else
            {
                points.Add(new Point(20, 0));
                points.Add(new Point(40, 0));
                points.Add(new Point(20, 20));
            }
            return(points);
        }
Exemple #48
0
        public static void Main(string[] args)
        {
            PointCollection AllPoints = new PointCollection();

            AllPoints.Add(new KMeans.DataStructures.Point(0, 1, 1.5));
            AllPoints.Add(new KMeans.DataStructures.Point(1, 5, 4));
            AllPoints.Add(new KMeans.DataStructures.Point(2, 2, 9));
            AllPoints.Add(new KMeans.DataStructures.Point(3, 4, 3));
            AllPoints.Add(new KMeans.DataStructures.Point(4, 4, 4));
            AllPoints.Add(new KMeans.DataStructures.Point(5, 6, 1.8));
            AllPoints.Add(new KMeans.DataStructures.Point(6, 7, 13));
            List <PointCollection> KMeansResult = KMeans.DataStructures.KMeans.DoKMeans(AllPoints, 2);

            foreach (var PC in KMeansResult)
            {
                foreach (var point in PC)
                {
                    Console.WriteLine("Centr = [{0};{1}] point {2}", PC.Centroid.X, PC.Centroid.Y, point);
                }
            }
            Console.WriteLine("Введите точку, принадлежность которой хотите проверить");
            Console.WriteLine("Принадлежит кластеру {0}", BelongsToCluster(KMeansResult, new Point(7, double.Parse(Console.ReadLine(), System.Globalization.CultureInfo.InvariantCulture), double.Parse(Console.ReadLine(), System.Globalization.CultureInfo.InvariantCulture))));
        }
        //0,50 0,139 85,189 170,139 170,50 85,0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var width = value as double?;
            var height = parameter as double?;
            var points = new PointCollection();

            if (width.HasValue && height.HasValue)
            {
                var halfX = width / 2;
                var sideLength = (double)height * .47;
                var triangleHeight = (double)(height - sideLength) / 2;

                points.Add(new Point((double)halfX, 0));
                points.Add(new Point((double)width, triangleHeight));
                points.Add(new Point((double)width, triangleHeight + sideLength));
                points.Add(new Point((double)halfX, (double)height));
                points.Add(new Point(0, triangleHeight + sideLength));
                points.Add(new Point(0, triangleHeight));
            }

            return points;
        }
        private static PointCollection ReadRing( JsonArray points )
        {
            points.RequireArgument<JsonArray>( "points" ).NotNull<JsonArray>();

            PointCollection ringCoords = new PointCollection();
            foreach( JsonValue entry in points )
            {
                JsonArray coordinates = entry as JsonArray;
                ringCoords.Add( ReadPoint( coordinates ) );
            }
            return ringCoords;
        }
        public static PointCollection ReadLineString( JsonArray points )
        {
            points.RequireArgument<JsonArray>( "points" ).NotNull<JsonArray>();

            PointCollection linestring = new PointCollection();
            foreach( JsonValue entry in points )
            {
                JsonArray coordinates = entry as JsonArray;
                linestring.Add(ReadPoint(coordinates));
            }
            return linestring;
        }
Exemple #52
0
 public PointCollection BarrelOutline(double inc)
 {
     PointCollection pc = new PointCollection();
     double phse = rad * Phase;
     double lastr = 0;
     double r;
     double tp;
     double a = 0;
     Point pd;
     int N = (int)Math.Floor(1.0 / inc);
     for (double i = 1; i < N; i++)
     {
         double f = i * inc;
         r = CalcR(f, 0);
         a = f * twopi + phse;
         tp = ToolPosition + r - lastr;
         pd = new Point(tp * Math.Cos(a), tp * Math.Sin(a));
         pc.Add(pd);
         lastr = r;
     }
     r = CalcR(1.0, 0);
     a = twopi + phse;
     tp = ToolPosition + r - lastr;
     pd = new Point(tp * Math.Cos(a), tp * Math.Sin(a));
     pc.Add(pd);
     return pc;
 }
        public static PointCollection GetSelectionPolygon(Rect topRect, Rect bottomRect, double width, double offsetX, double lineInterval)
        {
            double lineIntervalCompensation = 0;
            if(lineInterval < 1)
            {
                lineIntervalCompensation = 1 - lineInterval;
            }
            double topRectCompensation = topRect.Height * lineIntervalCompensation;
            double bottmRectCompensation = bottomRect.Height * lineIntervalCompensation;

            var pointCollection = new PointCollection();
            if (topRect.Top < bottomRect.Top)
            {
                pointCollection.Add(new Point(offsetX, topRect.Bottom));
                pointCollection.Add(new Point(topRect.Left, topRect.Bottom));
                pointCollection.Add(new Point(topRect.Left, topRect.Top + topRectCompensation));
                pointCollection.Add(new Point(width - offsetX, topRect.Top + topRectCompensation));
                pointCollection.Add(new Point(width - offsetX, bottomRect.Top + bottmRectCompensation));
                pointCollection.Add(new Point(bottomRect.Right, bottomRect.Top + bottmRectCompensation));
                pointCollection.Add(new Point(bottomRect.Right, bottomRect.Bottom));
                pointCollection.Add(new Point(offsetX, bottomRect.Bottom));
            }
            else
            {
                pointCollection.Add(new Point(topRect.Left, topRect.Bottom));
                pointCollection.Add(new Point(topRect.Left, topRect.Top + topRectCompensation));
                pointCollection.Add(new Point(bottomRect.Right, bottomRect.Top + bottmRectCompensation));
                pointCollection.Add(new Point(bottomRect.Right, bottomRect.Bottom));
            }
            return pointCollection;
        } 
        /// <summary>
        /// The draw line.
        /// </summary>
        /// <param name="points">
        /// The points.
        /// </param>
        /// <param name="stroke">
        /// The stroke.
        /// </param>
        /// <param name="thickness">
        /// The thickness.
        /// </param>
        /// <param name="dashArray">
        /// The dash array.
        /// </param>
        /// <param name="lineJoin">
        /// The line join.
        /// </param>
        /// <param name="aliased">
        /// The aliased.
        /// </param>
        public void DrawLine(
            IList<ScreenPoint> points,
            OxyColor stroke,
            double thickness,
            double[] dashArray,
            OxyPenLineJoin lineJoin,
            bool aliased)
        {
            var e = new Polyline();
            this.SetStroke(e, stroke, thickness, lineJoin, dashArray, aliased);

            var pc = new PointCollection();
            foreach (ScreenPoint p in points)
            {
                pc.Add(p.ToPoint(aliased));
            }

            e.Points = pc;

            this.Add(e);
        }
        /// <summary>
        /// The draw polygon.
        /// </summary>
        /// <param name="points">
        /// The points.
        /// </param>
        /// <param name="fill">
        /// The fill.
        /// </param>
        /// <param name="stroke">
        /// The stroke.
        /// </param>
        /// <param name="thickness">
        /// The thickness.
        /// </param>
        /// <param name="dashArray">
        /// The dash array.
        /// </param>
        /// <param name="lineJoin">
        /// The line join.
        /// </param>
        /// <param name="aliased">
        /// The aliased.
        /// </param>
        public void DrawPolygon(
            IList<ScreenPoint> points,
            OxyColor fill,
            OxyColor stroke,
            double thickness,
            double[] dashArray,
            OxyPenLineJoin lineJoin,
            bool aliased)
        {
            var po = new Polygon();
            this.SetStroke(po, stroke, thickness, lineJoin, dashArray, aliased);

            if (fill != null)
            {
                po.Fill = this.GetCachedBrush(fill);
            }

            var pc = new PointCollection();
            foreach (ScreenPoint p in points)
            {
                pc.Add(p.ToPoint(aliased));
            }

            po.Points = pc;

            this.Add(po);
        }
Exemple #56
0
 public static bool ConvertCollectionType(object value, Type targetType, out object result)
 {
   result = value;
   if (value == null)
     return true;
   if (targetType == typeof(PointCollection))
   {
     PointCollection coll = new PointCollection();
     string text = value.ToString();
     string[] parts = text.Split(new[] { ',', ' ' });
     for (int i = 0; i < parts.Length; i += 2)
     {
       Point p = new Point(Int32.Parse(parts[i]), Int32.Parse(parts[i + 1]));
       coll.Add(p);
     }
     result = coll;
     return true;
   }
   return false;
 }
        private void switchBaseMapLayer(TiledMapServiceLayer baseMapLayer, Envelope newExtent, List<Layer> oldBasemapLayers)
        {
            if (Map == null)
                return;

            // 1. Save the operational layers (We assume a single base layer)
            System.Collections.Generic.Stack<Layer> layers = new System.Collections.Generic.Stack<Layer>();
            for (int i = Map.Layers.Count - 1; i >= 0; i--)
            {
                Layer l = Map.Layers[i];
                if (oldBasemapLayers.Contains(l))
                    continue;

                Map.Layers.RemoveAt(i);
                layers.Push(l);
            }

            // 2. Clear the layers collection
            Map.Layers.Clear();

            // 3. Set the extent
            bool spatialReferenceUnchanged = Map.SpatialReference.Equals(newExtent.SpatialReference);
            Map.Extent = newExtent;

            // 4a. Set layer id if this is not set
            if (string.IsNullOrEmpty(baseMapLayer.ID) || (!string.IsNullOrEmpty(baseMapLayer.ID) && Map.Layers[baseMapLayer.ID] != null))
                baseMapLayer.ID = Guid.NewGuid().ToString("N");

            // 4. Add the new base map
            Map.Layers.Add(baseMapLayer);

            // 5. Re-add the operational layers         
            while (layers.Count > 0)
            {
                Layer layer = layers.Pop();
                if (!spatialReferenceUnchanged)
                {
                    //reproject graphics layers that are not feature layers 
                    // Feature layers support reprojection
                    if (layer is GraphicsLayer && !(layer is FeatureLayer))
                    {
                        GraphicsLayer graphicsLayer = layer as GraphicsLayer;
                        if (graphicsLayer.Graphics.Count > 0)
                        {
                            GeometryServiceOperationHelper helper = new GeometryServiceOperationHelper(
                                                                                                        new ConfigurationStoreHelper().GetGeometryServiceUrl(ConfigurationStore));
                            helper.ProjectGraphicsCompleted += (o, e) =>
                            {
                                GraphicsLayer targetLayer = e.UserState as GraphicsLayer;
                                if (targetLayer != null)
                                {
                                    targetLayer.Graphics.Clear();
                                    foreach (Graphic graphic in e.Graphics)
                                        targetLayer.Graphics.Add(graphic);
                                }
                            };
                            helper.ProjectGraphics(graphicsLayer.Graphics, newExtent.SpatialReference, graphicsLayer);
                        }

                        // update the map spatial reference on custom layers
                        ICustomGraphicsLayer customGraphicsLayer = layer as ICustomGraphicsLayer;
                        if (customGraphicsLayer != null)
                            customGraphicsLayer.MapSpatialReference = Map.SpatialReference;
                        else
                        {
                            HeatMapLayerBase heatMapLayer = layer as HeatMapLayerBase;
                            if (heatMapLayer != null)
                                heatMapLayer.MapSpatialReference = Map.SpatialReference;
                        }
                    }
                    else
                    {
                        HeatMapLayerBase heatMapLayer = layer as HeatMapLayerBase;
                        if (heatMapLayer != null && heatMapLayer.HeatMapPoints.Count > 0)
                        {
                            GeometryServiceOperationHelper helper = new GeometryServiceOperationHelper(new ConfigurationStoreHelper().GetGeometryServiceUrl(ConfigurationStore));
                            helper.ProjectPointsCompleted += (o, e) =>
                            {
                                PointCollection points = new PointCollection();

                                foreach (MapPoint item in e.Points)
                                {
                                    if (item != null)
                                        points.Add(item);
                                }

                                heatMapLayer.HeatMapPoints = points;
                                heatMapLayer.MapSpatialReference = points[0].SpatialReference;
                                heatMapLayer.Refresh();
                            };
                            helper.ProjectPoints(heatMapLayer.HeatMapPoints, newExtent.SpatialReference);
                        }
                    }
                }
                Map.Layers.Add(layer);
            }
        }
        /// <summary>
        /// Extracts a polygon from the input element and applies style information to the placemark descriptor.
        /// </summary>
        /// <param name="kmlStyle">KML Style information.</param>
        /// <param name="geomElement">Polygon geometry information.</param>
		/// <returns>A PlacemarkDescriptor object representing the feature.</returns>
        private static PlacemarkDescriptor ExtractLatLonBox(KMLStyle kmlStyle, XElement geomElement)
        {
			XNamespace kmlNS = geomElement.Name.Namespace;
			ESRI.ArcGIS.Client.Geometry.Polygon polygon = new Polygon();
            double? north = null, south = null, east = null, west = null;
            double temp;
            XElement boundary;

            // Extract box values
            boundary = geomElement.Element(kmlNS + "north");
            if (boundary != null)
            {
                if (double.TryParse(boundary.Value, System.Globalization.NumberStyles.Float, CultureInfo.InvariantCulture, out temp))
                    north = temp;
            }
            boundary = geomElement.Element(kmlNS + "south");
            if (boundary != null)
            {
                if (double.TryParse(boundary.Value, System.Globalization.NumberStyles.Float, CultureInfo.InvariantCulture, out temp))
                    south = temp;
            }
            boundary = geomElement.Element(kmlNS + "east");
            if (boundary != null)
            {
                if (double.TryParse(boundary.Value, System.Globalization.NumberStyles.Float, CultureInfo.InvariantCulture, out temp))
                    east = temp;
            }
            boundary = geomElement.Element(kmlNS + "west");
            if (boundary != null)
            {
                if (double.TryParse(boundary.Value, System.Globalization.NumberStyles.Float, CultureInfo.InvariantCulture, out temp))
                    west = temp;
            }

            if (north.HasValue && south.HasValue && east.HasValue && west.HasValue)
            {
                ESRI.ArcGIS.Client.Geometry.PointCollection pts = new PointCollection();
                MapPoint mp1 = new MapPoint(west.Value, north.Value);
                pts.Add(mp1);
                MapPoint mp2 = new MapPoint(east.Value, north.Value);
                pts.Add(mp2);
                MapPoint mp3 = new MapPoint(east.Value, south.Value);
                pts.Add(mp3);
                MapPoint mp4 = new MapPoint(west.Value, south.Value);
                pts.Add(mp4);

                polygon.Rings.Add(pts);

                // Create symbol and use style information
                PolygonSymbolDescriptor sym = new PolygonSymbolDescriptor();
                sym.style = kmlStyle;

                // Create feature descriptor from geometry and other information
                return new PlacemarkDescriptor()
                {
                    Geometry = polygon,
                    Symbol = sym
                };
            }

            return null;
        }
        private void ReportServices_DailyGrab_GenVehicleData_SOC()
        {
            GetChartData gd = new GetChartData();

            DateTime dt1 = new DateTime(2015, 8, 22);

               // DataTable dataTable = gd.GetSoCDt(194, dt1);
            DataTable dataTable = gd.Dt_DailyGrab_GetSoC(194, dt1, 100);

            //string mainTitle = string.Format("Soc Daily - {0}", dt.ToString("MM/dd/yy"));
            //string subTitle = string.Format("{0} - {1}", v.CustomerName, v.Vin);
            //hcVendas.Title = new Title(mainTitle);
            //hcVendas.SubTitle = new SubTitle(subTitle);

            hcVendas.Theme = "grid";
            hcVendas.Legend = new Legend { align = Align.right, layout = Layout.vertical, verticalAlign = VerticalAlign.top, x = -10, y = 70, borderWidth = 0 };
            hcVendas.Appearance = new Appearance { renderTo = "container", animation = false };
            hcVendas.YAxis.Add(new YAxisItem { title = new Title("SoC %") });

            hcVendas.XAxis.Add(new XAxisItem { type = AxisDataType.datetime, dateTimeLabelFormats = new DateTimeLabelFormats { hour = "%H" }, title = new Title("Time in Hours") });

             //   hcVendas.Tooltip = new ToolTip("Highcharts.dateFormat("%H:%M", this.x) +": "+ this.y");

            //Get point collection
            var pointCollectionSocMin = new PointCollection();
            var pointCollectionSocMax = new PointCollection();
            var pointCollectionSocDas = new PointCollection();

            foreach (DataRow row in dataTable.Rows)
            {
                //pointCollectionSocMin.Add(new Point(Convert.ToInt64((DateTime.Parse(row["Time_Occur"].ToString()).Subtract(new DateTime(2015, 1, 1))).TotalMilliseconds), Convert.ToDouble(row["SocMin"])));
                //pointCollectionSocMax.Add(new Point(Convert.ToInt64((DateTime.Parse(row["Time_Occur"].ToString()).Subtract(new DateTime(2015, 1, 1))).TotalMilliseconds), Convert.ToDouble(row["SocMax"])));
                //pointCollectionSocDas.Add(new Point(Convert.ToInt64((DateTime.Parse(row["Time_Occur"].ToString()).Subtract(new DateTime(2015, 1, 1))).TotalMilliseconds), Convert.ToDouble(row["SocDash"])));

                pointCollectionSocMin.Add(new Point(Convert.ToInt64((DateTime.Parse(row["Time_Occur"].ToString()).Subtract(new DateTime(2015, 1, 1))).TotalMilliseconds), Convert.ToDouble(row["PCes_usi_SoCmin_pct"])));
                pointCollectionSocMax.Add(new Point(Convert.ToInt64((DateTime.Parse(row["Time_Occur"].ToString()).Subtract(new DateTime(2015, 1, 1))).TotalMilliseconds), Convert.ToDouble(row["PCes_usi_SoCmax_pct"])));
                pointCollectionSocDas.Add(new Point(Convert.ToInt64((DateTime.Parse(row["Time_Occur"].ToString()).Subtract(new DateTime(2015, 1, 1))).TotalMilliseconds), Convert.ToDouble(row["PCbo_usi_DashSOC_pct"])));
                // pointCollection.Add(new Point(DateTime.Parse(row["Time_Occur"].ToString()), Convert.ToDouble(row["SocMin"])));
            }

            //Add data to serie
            var series = new Collection<Serie> { new Serie { name = "PCes_usi_SoCmin_pct", data = pointCollectionSocMin.ToArray() }, new Serie { name = "PCes_usi_SoCmax_pct", data = pointCollectionSocMax.ToArray() }, new Serie { name = "PCbo_usi_DashSOC_pct", data = pointCollectionSocDas.ToArray() } };
            hcVendas.PlotOptions = new PlotOptionsLine { marker = new Marker { enabled = false }, dataLabels = new DataLabels { enabled = false } };

            //Bind the control
            hcVendas.DataSource = series;
            hcVendas.DataBind();
        }
Exemple #60
0
        /// <summary>
        /// Add a new point to points collection (representing a stroke), keeping the whole stroke antialiased.
        /// </summary>
        /// <param name="x">X point coordinate</param>
        /// <param name="y">Y point coordinate</param>
        /// <param name="isLastPoint">Set to true when adding last point of the stroke</param>
        /// <param name="points">Stroke to which the point is added</param>
        /// <returns></returns>
        public static int AddPixels(double x, double y, bool isLastPoint, ref PointCollection points)
        {
            double    xNew;
            double    yNew;
            double    x1;
            double    y1;
            float    nSeg;
    
            if  ( points.Count == 0 )
            {
                points.Add(new Point(x, y));
                _previousLocation.X = x;
                _previousLocation.Y = y;
                return  1;
            }
    
            var dx = Math.Abs( x - points[points.Count-1].X );
            var dy = Math.Abs( y - points[points.Count-1].Y );
    
            if  ( dx + dy < 2.0f )
                return 0;
    
            if ( dx + dy > 100.0f * SEGMENT_DIST_2 )
                return 0;
    
            if  ( (dx + dy) < SEGMENT_DIST_1 )
            {
                points.Add(new Point(x, y));

                _previousLocation.X = x;
                _previousLocation.Y = y;
                return  1;
            }
    
            if ( (dx + dy) < SEGMENT_DIST_2 )
                nSeg = SEGMENT2;
            else if ( (dx + dy) >= SEGMENT_DIST_3 )
                nSeg = SEGMENT4;
            else
               nSeg = SEGMENT3;
            int     nPoints = 0;
            double EPSILON = 0.0001;
            for (var i = 1; i < nSeg; i++)
            {
                x1 = _previousLocation.X + ((x - _previousLocation.X)*i ) / nSeg;  //the point "to look at"
                y1 = _previousLocation.Y + ((y - _previousLocation.Y)*i ) / nSeg;  //the point "to look at"
       
                xNew = points[points.Count-1].X + (x1 - points[points.Count-1].X) / nSeg;
                yNew = points[points.Count-1].Y + (y1 - points[points.Count-1].Y) / nSeg;

                if ( Math.Abs(xNew - points[points.Count-1].X) > EPSILON || Math.Abs(yNew - points[points.Count-1].Y) > EPSILON )
                {
                    points.Add(new Point(xNew, yNew));
                    nPoints++;
                }
            }
    
            if ( isLastPoint )
            {
                // add last point
                if (Math.Abs(x - points[points.Count - 1].X) > EPSILON || Math.Abs(y - points[points.Count - 1].Y) > EPSILON)
                {
                    points.Add(new Point(x, y));
                    nPoints++;
                }
            }
    
            _previousLocation.X = x;
            _previousLocation.Y = y;
            return nPoints;
        }