BLOG.CSHARPHELPER.COM: Draw a Bézier curve "by hand" that matches the one drawn by the Graphics object's DrawBezier method in C#
Draw a Bézier curve "by hand" that matches the one drawn by the Graphics object's DrawBezier method in C#
A Bézier curve is a spline, a smooth curve whose shape is determined by control points. For this kind of cubic Bézier curve, the control points determine the curve's start and end points, and the directions of the tangents at those points. (See the picture on the right.)
The Graphics object provides a DrawBezier method that takes the four control points as parameters and draws the curve. Sometimes, however, it's useful to be able to plot points on the curve. For example, if you wanted to make text follow the curve, you would need to generate points along it and not just draw the curve in a single call to DrawBezier.
The points on the cubic Bézier curve are generated by the following equation where t varies from 0 to 1:
Here P0, P1, P2, and P3 are the control points. (Plug in the corresponding X and Y values to get the resulting points' coordinates.)
This example includes a BezierStuff class that provides a static DrawBezier method to draw a Bézier curve. The following code shows that method and its helper X and Y functions.
This version also draws the lines between the control points. In a real application, you would want to remove that code and do something with the curve's points other than just connecting them.
The main program uses the following code to draw a curve defined by control points selected by the user. It first draws the curve using the Graphics class's DrawBezier method with a thick pen. It then draws the same curve using the new DrawBezier method and a thin pen so you can see it on top of the other curve.
// Draw the currently selected points. // If we have four points, draw the Bezier curve. private void picCanvas_Paint(object sender, PaintEventArgs e) { e.Graphics.Clear(picCanvas.BackColor); if (NextPoint >= 4) { // Draw a spline the easy way. using (Pen thick_pen = new Pen(Color.Yellow, 7)) { e.Graphics.DrawBezier(thick_pen, Points[0], Points[1], Points[2], Points[3]); }
// Draw a spline the hard way. BezierStuff.DrawBezier(e.Graphics, Pens.Black, 0.01f, Points[0], Points[1], Points[2], Points[3]); }
// Draw the control points. for (int i = 0; i < NextPoint; i++) { e.Graphics.FillRectangle(Brushes.White, Points[i].X - 3, Points[i].Y - 3, 6, 6); e.Graphics.DrawRectangle(Pens.Black, Points[i].X - 3, Points[i].Y - 3, 6, 6); } }
Comments