Search code examples
c#algorithmbeziersplinenurbs

Draw splines with a list of points in a 2D Array


I've looked into splines, nurbs and Bezier curves bit I can't find an algorithm that fits my needs. I would appreciate help with an algorithm or function that can draw a curve based on points in a 2D array.

Example:

First starting point in my array : ex arr[1,2] = new Point(1,2)

0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0

Output:

0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0
0,0,1,0,0,0,0,1,0,1,0,0,0,0,0,0
0,0,0,1,0,0,0,1,0,0,1,0,0,0,0,0
0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0
0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0


Solution

  • There are two parts of this question: defining a smooth curve that goes through those points, and then drawing that curve into your array.

    A common curve type that goes through several defined points is the Catmull-Rom spline. You might want to see if this meets your needs.

    To define your Catmull-Rom spline, you'd want to scan your 2D array from left to right, and wherever there is a 1, add a point to the spline. You'll also need to come up with a curve parameterization. Using the column number as the parameter value for each point would probably give good results.

    In terms of drawing, there are a few different approaches. Catmull-Rom splines are parametric, so you could try computing the point on the curve at a lot of t values, and setting the corresponding array location. If you have a line-drawing primitive implemented (like Bresenham line drawing), you can compute fewer points on the spline and fill in with lines. There are also other methods, like decomposing splines into beziers or scanline methods, but they're more complicated and probably unnecessary.