Freigeben über


Curved Polygons in WPF!

I found something on the web https://www.antigrain.com/research/bezier_interpolation/index.html about using Bezier curves to build polygons with smooth corners. Anyways, I ported this to WPF and it works very well! Basically, consider the last point (point0), current point (point1), next point (point2) and the point after that (point3), you can compute each Bezier segment as follows:

     public static BezierSegment PolygonSegment(Vector point0, Vector point1, Vector point2, Vector point3, double smoothValue) {
      var c1 = (point0 + point1) / 2d;
      var c2 = (point1 + point2) / 2d;
      var c3 = (point2 + point3) / 2d;

      var len1 = (point1 - point0).Length;
      var len2 = (point2 - point1).Length;
      var len3 = (point3 - point2).Length;

      var k1 = len1 / (len1 + len2);
      var k2 = len2 / (len2 + len3);

      var m1 = c1 + (c2 - c1) * k1;
      var m2 = c2 + (c3 - c2) * k2;

      var ctrl1 = m1 + (c2 - m1) * smoothValue + point1 - m1;
      var ctrl2 = m2 + (c2 - m2) * smoothValue + point2 - m2;
      var curve = new BezierSegment();
      curve.Point1 = (Point) ctrl1;
      curve.Point2 = (Point) ctrl2;
      curve.Point3 = (Point) point2;
      return curve;
    }

 

Simply loop through your points to create your polygon, here is some code in a physics engine I’m doing:

       figure.StartPoint = points[(0 + 1) % points.Count].centerPoint;
      var segments = new PathSegmentCollection();
      for (int i = 0; i < points.Count; i++) {
        var point0 = points[(i + 0) % points.Count].centerPoint;
        var point1 = points[(i + 1) % points.Count].centerPoint;
        var point2 = points[(i + 2) % points.Count].centerPoint;
        var point3 = points[(i + 3) % points.Count].centerPoint;
        segments.Add(Extensions.PolygonSegment((Vector) point0, (Vector) point1, (Vector)point2, (Vector) point3, .7));
        var cp = point0;
        topLeft = topLeft.Min(cp);
        bottomRight = bottomRight.Max(cp);
      }
      figure.Segments = segments;

where figure is the only path figure of a PathGeometry.

Check out the cool blob-like results:

clip_image002

Comments

  • Anonymous
    March 14, 2011
    can i get  a sample project on this