Draw a curve with control points

 

Environment: VC++ 6.0

One friend asks me how to draw a curve with a couple of mouse clicking. I know there is way called “cubic spline” to draw the curve based on the control points. I search through the internet, try to find out a piece of existing code. Unfortunately, though there are plenty of webpage talking about it, but few sites really give out the working code. I did found some Java code was presented with mess of the other UI handling code; however, I have not found any C/C++
code to finish this job so far. And I am not really a Java lover….

So I finish this piece of C++ header file called “spline.h”. Which is easy to use and light weight. All you need to do is:

  1. Include this header file into your C++ file.
  2. Create a spline object.
  3. Pump in the control points.
  4. Gernearte a curve by a simple code line: spline.generate();
  5. Get the curve points to your array.
  6. Paint the curve to your DC.

This is so easy and handy for my future UI curve drawing, and you can also adjust the curve smoothness degree by setting a defined factor in spline.h.

A known bug: the control points should be more than one, if only one control point are pass to the spline, it will crash, I will appreciate it if anybody fix the bug.

Here is the code where I generate the curve, MFC CArray is used for my points array

//create a spline object
Spline spline(m_ControlPoints.GetData(),
m_ControlPoints.GetSize());
//generate a curve
spline.Generate();
//get the curve points number
m_CurvePoints.SetSize(spline.GetCurveCount());
//get the points number
int PointCount = 0;
spline.GetCurve(m_CurvePoints.GetData(),
PointCount);
//paint the curve
UpdateDialog(pDC->m_hDC);

Downloads

Download source - 34 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read