Home Search   What's New Index Books Links Q & A Newsletter Banners   Feedback Tip Jar MSDN Visual Basic Community

Title Draw a smooth closed curve by hand in VB .NET This example shows how to draw a smooth closed curve by hand in VB .NET. smooth curve, smooth closed curve, spline, cardinal spline, Bezier curve, tension Graphics, VB.NET

This approach connects a series of points with Bezier curves. The interior control points are chosen so the curves meet smoothly. These control points lie along a line parallel to the line connecting the points' neighbors. For example, suppose point p2 lies between p1 and p3. When drawing the Bezier curve between points p2 and p3, the control point after p2 lies along a line starting at p2 and going in the same direction as the line between p1 and p3. The distance along this line that the point lies is determined by a "tension" factor. See the code for details.

' Draw a closed cardinal spline built from connected Bezier
' curves.
Public Sub DrawClosedCurve(ByVal gr As Graphics, ByVal _
the_pen As Pen, ByVal dt As Single, ByVal tension As _
Single, ByVal pts() As PointF)
Dim control_scale As Single = CSng(tension / 0.5 * _
0.175)
Dim pt, pt_before, pt_after, pt_after2, Di, DiPlus1 As _
PointF
Dim p1, p2, p3, p4 As PointF
Dim num_pts As Integer = pts.Length
For i As Integer = 0 To pts.GetUpperBound(0)
pt_before = pts((i - 1 + num_pts) Mod num_pts)
pt = pts(i)
pt_after = pts((i + 1) Mod num_pts)
pt_after2 = pts((i + 2) Mod num_pts)

p1 = pt
p4 = pt_after

Di.X = pt_after.X - pt_before.X
Di.Y = pt_after.Y - pt_before.Y
p2.X = pt.X + control_scale * Di.X
p2.Y = pt.Y + control_scale * Di.Y

DiPlus1.X = pt_after2.X - pts(i).X
DiPlus1.Y = pt_after2.Y - pts(i).Y
p3.X = pt_after.X - control_scale * DiPlus1.X
p3.Y = pt_after.Y - control_scale * DiPlus1.Y

DrawBezier(gr, the_pen, dt, p1, p2, p3, p4)
Next i
End Sub

See Draw a Bezier curve by hand in VB .NET for information on drawing Bezier curves.

Also see Draw a smooth curve by hand in VB .NET for information on drawing non-closed curves.

For more information on graphics programming in Visual Basic 6, see my book Visual Basic Graphics Programming.