[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Draw a Bezier curve in C#

[Draw a Bezier curve in C#]

This example shows how to use the Graphics class's DrawBezier method to draw a Bezier curve. A Bezier curve connects two end points with a smooth curve. The shape of the curve is determined by two control points. The control points influence the shape of the curve, but lie on it.

When you click on the program's PictureBox, the following code saves the point you clicked.

// The endpoints are points 0 and 3. // The interior control points are points 1 and 2. private PointF[] Points = new PointF[4]; // The index of the next point to define. private int NextPoint = 0; // Select a point. private void picCanvas_MouseClick(object sender, MouseEventArgs e) { // If we're starting a new set of four points, // get the first point. if (NextPoint > 3) NextPoint = 0; // Save this point. Points[NextPoint].X = e.X; Points[NextPoint].Y = e.Y; // Move to the next point. NextPoint++; // Redraw. picCanvas.Refresh(); }

This code defines the Points array and the variable NextPoint that holds the index of the next point in the array. The PictureBox control's MouseClick event handler stores the point you clicked in Points[NextPoint] and increments NextPoint. It then refreshes the PictureBox to make the following Paint event handler execute.

// Draw the currently selected points. // If we have four points, draw the Bezier curve. private void picCanvas_Paint(object sender, PaintEventArgs e) { e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; e.Graphics.Clear(picCanvas.BackColor); if (NextPoint >= 4) { // Draw the curve. e.Graphics.DrawBezier(Pens.Red, 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); } }

A Bezier curve needs two end points and two control points, so the program first checks that you have selected 4 points. If you have, it calls the Graphics object's DrawBezier method to draw the curve. It passes the method the pen it should use, the first end point, the two control points, and the last end point.

The method then draws the points so you can see how they affect the curve's shape.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.