[C# Helper]
Index Books FAQ Contact About Rod
[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]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

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

Title: Draw a smooth curve connecting points in C#

[Draw a smooth curve connecting points in C#]

The Graphics class's DrawCurve method draws a smooth curve connecting a sequence of points.

The type of curve drawn is called a spline. In general, a spline is a smooth curve with a shape determined by a collection of control points. In some splines, the control points guide the shape of the curve but the curve doesn't touch them. The DrawCurve method draws a spline that passes through each of its control points.

This example uses the following code to let you select points.

// The points selected by the user. private List<Point> Points = new List<Point>(); // Select a point. private void Form1_MouseClick(object sender, MouseEventArgs e) { Points.Add(e.Location); Refresh(); }

Each time you click the mouse, the MouseClick event handler adds the point to the Points list. It then refreshes the form to make it execute the following Paint event handler.

private void Form1_Paint(object sender, PaintEventArgs e) { e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; // Draw the points. foreach (Point point in Points) e.Graphics.FillEllipse(Brushes.Black, point.X - 3, point.Y - 3, 5, 5); if (Points.Count < 2) return; // Draw the curve. e.Graphics.DrawCurve(Pens.Red, Points.ToArray()); }

This code loops through the points and draws circles for each. Then if the Points list contains fewer than 2 points, the method exits. Otherwise it calls the list's ToArray method to create an array of points and passes them to the call to DrawCurve.

The only other piece of code is the following method, which executes when you select the Curve menu's New command.

// Start a new point list. private void mnuCurveNew_Click(object sender, EventArgs e) { Points = new List<Point>(); Refresh(); }

This code simply creates a new empty Points list and refreshes the form.

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

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