private void clipBtn_Click(object sender, RoutedEventArgs e) { CGPolygon polygon = new CGPolygon(PolygonPoints); List <CGLine> segments = new List <CGLine>(); foreach (var l in this.Lines) { Point a = new Point(l.X1, l.Y1); Point b = new Point(l.X2, l.Y2); CGLine S = new CGLine(a, b); segments.Add(S); } List <Point> pList = new List <Point>(); var x = polygon.Clip(segments); foreach (var item in x) { Line ln = new Line(); ln.X1 = item.A.X; ln.Y1 = item.A.Y; ln.X2 = item.B.X; ln.Y2 = item.B.Y; ln.Stroke = Brushes.Pink; ln.StrokeThickness = 2; mainContainer.Children.Add(ln); } }
private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { switch (DrawingMode) { case Mode.Polygon: Point p = e.GetPosition(mainContainer); PolygonPoints.Add(p); if (PolygonPoints.Count > 1) { this.PolygonRadioBtn.IsEnabled = true; } if (!CGPolygon.PolygonIsConvex(PolygonPoints)) { MessageBox.Show("Polygon is not convex"); PolygonPoints.Remove(p); break; } var circle = new Ellipse { Stroke = Brushes.Black, StrokeThickness = 2, }; Canvas.SetLeft(circle, p.X - 2); Canvas.SetTop(circle, p.Y - 2); mainContainer.Children.Add(circle); break; case Mode.DrawLine: Point lP = e.GetPosition(mainContainer); break; } }
public static bool PolygonIsConvex(List <Point> Points) { // For each set of three adjacent points A, B, C, // find the cross product AB · BC. If the sign of // all the cross products is the same, the angles // are all positive or negative (depending on the // order in which we visit them) so the polygon // is convex. bool got_negative = false; bool got_positive = false; int num_points = Points.Count; int B, C; for (int A = 0; A < num_points; A++) { B = (A + 1) % num_points; C = (B + 1) % num_points; double cross_product = CGPolygon.CrossProductLength(Points[A].X, Points[A].Y, Points[B].X, Points[B].Y, Points[C].X, Points[C].Y); if (cross_product < 0) { got_negative = true; } else if (cross_product > 0) { got_positive = true; } if (got_negative && got_positive) { return(false); } } // If we got this far, the polygon is convex. return(true); }