Click here to Skip to main content
15,885,278 members
Articles / Desktop Programming / WPF

Draw a Smooth Curve through a Set of 2D Points with Bezier Primitives

,
Rate me:
Please Sign up or sign in to vote.
4.94/5 (57 votes)
24 Mar 2009CPOL6 min read 441.5K   12.8K   148   57
Calculate piecewise Bezier curve control points to make it a spline

Image 1

Introduction

From time to time, I am faced with the question: how to draw a smooth curve through a set of 2D points? It seems strange, but we don't have out of the box primitives to do so. Yes, we can draw a polyline, Bezier polyline, or a piece-wise cardinal spline, but they are all not what is desired: polyline isn't smooth; with Bezier and cardinal spline, we have a headache with additional parameters like Bezier control points or tension. Very often, we don't have any data to evaluate these additional parameters. And, very often, all we need is to draw the curve which passes through the points given and is smooth enough. Let's try to find a solution.

We have interpolation methods at hand. The cubic spline variations, for example, give satisfactory results in most cases. We could use it and draw the result of the interpolation, but there are some nasty drawbacks:

  1. Cubic spline is a cubic polynomial, but Win32, .NET Forms, or WPF do not provide methods to draw a piecewise cubic polynomial curve. So, to draw that spline, we have to invent an effective algorithm to approximate a cubic polynomial with polyline, which isn't trivial (word “effective” is a point!).
  2. Cubic spline algorithms are usually designed to deal with functions in the Cartesian coordinates, y=f(x). This implies that the function is single valued; it isn't always appropriate.

On the other hand, the platform provides us with a suite of Bezier curve drawing methods. Bezier curve is a special representation of a cubic polynomial expressed in the parametric form (so it isn't the subject of single valued function restriction). Bezier curves start and end with two points often named “knots”; the form of the curve is controlled by two more points known as “control points”.

Bezier spline is a sequence of individual Bezier curves joined to form a whole curve. The trick to making it a spline is to calculate control points in such a way that the whole spline curve has two continuous derivatives.

I spent some time Googling for a code in any C-like language for a Bezier spline, but couldn't found any cool, ready-to-use code.

Here, we'll deal with open-ended curves, but the same approach could be applied to the closed curves.

Bezier Curve Representation

A Bezier curve on a single interval is expressed as:

$B(t)=(1-t)^3 P_0 +3(1-t)^2t P_1 +3(1-t)t^2 P_2 +t^3 P_3 \ldots (1)$

where t is in [0,1], and

  1. P0 – first knot point
  2. P1 – first control point (close to P0)
  3. P2 – second control point (close to P3)
  4. P3 – second knot point

The first derivative of (1) is:

$B'(t)=-3(1-t)^2 P_0 +3(3t^2 - 4t+1) P_1 + 3(2t-3t^2)P_2 +3t^2 P_3$

The second derivative of (1) is:

$B''(t)=6(1 - t)P_0 +3(6t-4)P_1+3(2 - 6t)P_2 +6tP_3$

Single Segment

If we have just two knot points, our "smooth" Bezier curve should be a straight line, i.e. in (1) the coefficients in the members with the power 2 and 3 should be zero. It's easy to deduce that its control points should be calculated as:

$3P_1 = 2P_0 + P_3 P_2 = 2P_1 - P_0$

Multiple Segments

This is the case where we have more than two points. One more time: to make a sequence of individual Bezier curves to be a spline, we should calculate Bezier control points so that the spline curve has two continuous derivatives at knot points.

Considering a set of piecewise Bezier curves with n+1 points and n subintervals, the (i-1)-th curve should connect to the i-th one. Now we will denote the points as follows:

  1. Piith knot point (i=1,..,n)
  2. P1i – first control point close to Pi
  3. P2i – second control point close to Pi

At the ith subinterval, the Bezier curve will be:

$B_i (t)=(1-t)^3 P_{i-1} +3(1-t)^2 tP1_i +3(1-t)t^2 P2_i +t^3 P_i \ldots (i=1,..,n)$

The first derivative at the ith subinterval is:

$B'_i (t) = -3(1-t)^2 P_i-1 +3(3t^2 - 4t+1)P1_i +3(2t-3t^2)P2_i +3t^2 P_i; \ldots (i=1,..,n)$

The first derivative continuity condition \(B'_{i-1}(1) = B'_i(0)\) gives:

$P1_i +P2_{i-1} = 2P{i-1}; \ldots (i=2,..,n) (2)$

The second derivative at the ith subinterval is:

$B''_i(t) = 6(1-t)P_{i-1} + 6(3t-2)P1_i + 6(1-3t)P2_i +6tP_i; \ldots (i=1,..,n)$

The second derivative continuity condition B’’i-1(1)=B’’i(0) gives:

$P1_{i-1} + 2P1_i = P2_i +2P2_{i-1}; \ldots (i=2,..,n) (3)$
P1i-1+2P1i=P2i+2P2i-1; (i=2,..,n) (3)

Then, as always with splines, we'll add two more conditions at the ends of the total interval. These will be the “natural conditions” B’’<sub>1</sub>(0) = 0 and B’’<sub>n</sub>(1) = 0.

$2P1_1 - P2_1 = P_0 (4) 2P2_n -P1_n = P_n \ldots (5)$
2P11-P21 = P0 (4) 2P2n-P1n = Pn (5)

Now, we have 2n conditions (2-5) for n control points P1 and n control points P2. Excluding P2, we'll have n equations for n control points P1:

$ \begin{align} 2P1_1 + P1_2 &= P_0 + 2P_1 P1_1 + 4P1_2 + P1_3 = 4P_1 + 2P_2 \\ P1_{i-1} + 4P1_i + P1_{i+1} &= 4P_{i-1} + 2P_i \ldots (6) \\ P1_{n-2} + 4P1_{n-1} + P1_n &= 4P_{n-2} + 2P_{n-1} 2P1_{n-1} + 7P1_n = 8P_{n-1} + P_n \end{align} $

System (6) is the tridiagonal one with the diagonal dominance, hence we can solve it by simple variable elimination without any tricks.

When P1 is found, P2 could be calculated from (2) and (5).

The Code

C#
/// <summary>
/// Bezier Spline methods
/// </summary>
public static class BezierSpline
{
	/// <summary>
	/// Get open-ended Bezier Spline Control Points.
	/// </summary>
	/// <param name="knots">Input Knot Bezier spline points.</param>
	/// <param name="firstControlPoints">Output First Control points
	/// array of knots.Length - 1 length.</param>
	/// <param name="secondControlPoints">Output Second Control points
	/// array of knots.Length - 1 length.</param>
	/// <exception cref="ArgumentNullException"><paramref name="knots"/>
	/// parameter must be not null.</exception>
	/// <exception cref="ArgumentException"><paramref name="knots"/>
	/// array must contain at least two points.</exception>
	public static void GetCurveControlPoints(Point[] knots,
		out Point[] firstControlPoints, out Point[] secondControlPoints)
	{
		if (knots == null)
			throw new ArgumentNullException("knots");
		int n = knots.Length - 1;
		if (n < 1)
			throw new ArgumentException
			("At least two knot points required", "knots");
		if (n == 1)
		{ // Special case: Bezier curve should be a straight line.
			firstControlPoints = new Point[1];
			// 3P1 = 2P0 + P3
			firstControlPoints[0].X = (2 * knots[0].X + knots[1].X) / 3;
			firstControlPoints[0].Y = (2 * knots[0].Y + knots[1].Y) / 3;

			secondControlPoints = new Point[1];
			// P2 = 2P1 – P0
			secondControlPoints[0].X = 2 *
				firstControlPoints[0].X - knots[0].X;
			secondControlPoints[0].Y = 2 *
				firstControlPoints[0].Y - knots[0].Y;
			return;
		}

		// Calculate first Bezier control points
		// Right hand side vector
		double[] rhs = new double[n];

		// Set right hand side X values
		for (int i = 1; i < n - 1; ++i)
			rhs[i] = 4 * knots[i].X + 2 * knots[i + 1].X;
		rhs[0] = knots[0].X + 2 * knots[1].X;
		rhs[n - 1] = (8 * knots[n - 1].X + knots[n].X) / 2.0;
		// Get first control points X-values
		double[] x = GetFirstControlPoints(rhs);

		// Set right hand side Y values
		for (int i = 1; i < n - 1; ++i)
			rhs[i] = 4 * knots[i].Y + 2 * knots[i + 1].Y;
		rhs[0] = knots[0].Y + 2 * knots[1].Y;
		rhs[n - 1] = (8 * knots[n - 1].Y + knots[n].Y) / 2.0;
		// Get first control points Y-values
		double[] y = GetFirstControlPoints(rhs);

		// Fill output arrays.
		firstControlPoints = new Point[n];
		secondControlPoints = new Point[n];
		for (int i = 0; i < n; ++i)
		{
			// First control point
			firstControlPoints[i] = new Point(x[i], y[i]);
			// Second control point
			if (i < n - 1)
				secondControlPoints[i] = new Point(2 * knots
					[i + 1].X - x[i + 1], 2 *
					knots[i + 1].Y - y[i + 1]);
			else
				secondControlPoints[i] = new Point((knots
					[n].X + x[n - 1]) / 2,
					(knots[n].Y + y[n - 1]) / 2);
		}
	}

	/// <summary>
	/// Solves a tridiagonal system for one of coordinates (x or y)
	/// of first Bezier control points.
	/// </summary>
	/// <param name="rhs">Right hand side vector.</param>
	/// <returns>Solution vector.</returns>
	private static double[] GetFirstControlPoints(double[] rhs)
	{
		int n = rhs.Length;
		double[] x = new double[n]; // Solution vector.
		double[] tmp = new double[n]; // Temp workspace.

		double b = 2.0;
		x[0] = rhs[0] / b;
		for (int i = 1; i < n; i++) // Decomposition and forward substitution.
		{
			tmp[i] = 1 / b;
			b = (i < n - 1 ? 4.0 : 3.5) - tmp[i];
			x[i] = (rhs[i] - x[i - 1]) / b;
		}
		for (int i = 1; i < n; i++)
			x[n - i - 1] -= tmp[n - i] * x[n - i]; // Backsubstitution.

		return x;
	}
}

Although I compiled this code in C# 3.0, I don’t see why it can’t be used without any modification in C# 2.0, and even in C# 1.0 if you remove the keyword “static” from the class declaration.

Note that the code uses the System.Windows.Point structure, so it is intended for use with Windows Presentation Foundation, and the using System.Windows; directive is required. But all you should do to use it with Windows Forms is to replace the System.Windows.Point type with System.Drawing.PointF. Equally, it is straightforward to convert this code to C/C++, if desired.

The Sample

The sample supplied with this article is a Visual Studio 2008 solution targeted at .NET 3.5. It contains a WPF Windows Application project designed to demonstrate some curves drawn with the Bezier spline above. You can select one of the curves from the combo box at the top of the window, experiment with the point counts, and set appropriate XY scales. You can even add your own curve, but this requires coding as follows:

  1. Add your curve name to the CurveNames enum.
  2. Add your curve implementation to the Curves region.
  3. Add a call to your curve in the OnRender override.

In the sample, I use Path elements on the custom Canvas to render the curve, but in a real application, you would probably use a more effective approach like visual layer rendering.

History

  • 18th December, 2008: Initial post
  • 23rd March, 2009: Second article revision with the following corrections and additions:
    1. The most important is the bug fix. This bug as well as its correction was found by Peter Lee. A lot of thanks to him! This bug produced visually distinguishable behavior in the case of small knot points count.
    2. GetCurveControlPoints now throw exceptions if invalid parameter is passed.
    3. Added special handling of the case where knots array has just two points
    4. Unit tests added.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
Russian Federation Russian Federation
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: Curl between 2 knots Pin
Oleg V. Polikarpotchkin7-Oct-09 20:24
Oleg V. Polikarpotchkin7-Oct-09 20:24 
GeneralRe: Curl between 2 knots Pin
Jean-LucM16-Oct-09 3:53
Jean-LucM16-Oct-09 3:53 
QuestionQuestion about the equation Pin
neo30816-Sep-09 12:29
neo30816-Sep-09 12:29 
AnswerRe: Question about the equation Pin
Oleg V. Polikarpotchkin16-Sep-09 19:36
Oleg V. Polikarpotchkin16-Sep-09 19:36 
GeneralRe: Question about the equation Pin
neo30818-Sep-09 3:34
neo30818-Sep-09 3:34 
GeneralVisual layer rendering. Pin
tinatran3022-Jul-09 16:28
tinatran3022-Jul-09 16:28 
GeneralRe: Visual layer rendering. Pin
Oleg V. Polikarpotchkin22-Jul-09 17:47
Oleg V. Polikarpotchkin22-Jul-09 17:47 
NewsI used this algorithm in a project very dear to me. Pin
Akatz71221-Jul-09 15:51
Akatz71221-Jul-09 15:51 
For the past few decades I have been writing a program to emulate a physical drawing toy which was called 'Magic Designer'. It drew curved shapes on paper. It is not spirograph, but came before that toy.

The latest version of my program is found on my website:
Magic Designer Overview [^]

It is open source, and to look at the source, please download only from SOURCE FORGE. The link is on my site. Everything on the web is also open source (unless it is on the server), since it is exposed by the browser.

Your program is written in C#. The languages I use are javascript for the web browser version of my program, and C for the Windows version (my Windows Gui is written in Euphoria language). And I adapted your program for both versions so I could smoothly join bezier segments together.

I want to THANK YOU very much. Smile | :) Smile | :) Smile | :)

Andrew Katz

GeneralExcellent Pin
Luc Pattyn25-Mar-09 0:58
sitebuilderLuc Pattyn25-Mar-09 0:58 
GeneralRe: Excellent Pin
Oleg V. Polikarpotchkin25-Mar-09 3:21
Oleg V. Polikarpotchkin25-Mar-09 3:21 
NewsA mistake in the last equation which causes a strange behavior (corrected) Pin
Peter Lee16-Mar-09 4:35
Peter Lee16-Mar-09 4:35 
GeneralRe: A mistake in the last equation which causes a strange behavior (corrected) Pin
Peter Lee16-Mar-09 4:47
Peter Lee16-Mar-09 4:47 
GeneralRe: A mistake in the last equation which causes a strange behavior (corrected) Pin
Oleg V. Polikarpotchkin18-Mar-09 23:55
Oleg V. Polikarpotchkin18-Mar-09 23:55 
GeneralRe: A mistake in the last equation which causes a strange behavior (corrected) Pin
twerd.ster12-Dec-09 7:51
twerd.ster12-Dec-09 7:51 
Questionalgorithm behavior Pin
bstrack9-Mar-09 13:45
bstrack9-Mar-09 13:45 
AnswerRe: algorithm behavior Pin
Oleg V. Polikarpotchkin9-Mar-09 18:36
Oleg V. Polikarpotchkin9-Mar-09 18:36 
GeneralNeed Help on the closed curves Pin
wang200226-Feb-09 15:08
wang200226-Feb-09 15:08 
GeneralRe: Need Help on the closed curves Pin
Oleg V. Polikarpotchkin27-Feb-09 17:14
Oleg V. Polikarpotchkin27-Feb-09 17:14 
GeneralRe: Need Help on the closed curves Pin
Oleg V. Polikarpotchkin1-Mar-09 4:27
Oleg V. Polikarpotchkin1-Mar-09 4:27 
GeneralGreat article Pin
Cedric Moonen18-Dec-08 8:12
Cedric Moonen18-Dec-08 8:12 
GeneralRe: Great article Pin
Oleg V. Polikarpotchkin18-Dec-08 16:58
Oleg V. Polikarpotchkin18-Dec-08 16:58 
GeneralVariable Names Pin
#realJSOP18-Dec-08 1:11
mve#realJSOP18-Dec-08 1:11 
GeneralRe: Variable Names Pin
Oleg V. Polikarpotchkin18-Dec-08 16:39
Oleg V. Polikarpotchkin18-Dec-08 16:39 
GeneralRe: Variable Names Pin
Herbert Sauro22-Dec-08 11:03
Herbert Sauro22-Dec-08 11:03 
AnswerRe: Variable Names Pin
Oleg V. Polikarpotchkin22-Dec-08 16:15
Oleg V. Polikarpotchkin22-Dec-08 16:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.