Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleDraw a Bezier curve
DescriptionThis example shows how to draw a Bezier curve in VB 6.
KeywordsBezier curve, spline, smooth, curve
CategoriesGraphics
 
A Bezier curve is defined by four control points p0, p1, p2, and p3. It starts at p0 heading toward p1, and ends at p3 coming from the direction of p2. You can define the Bezier curve by the following equation:

    p0 * (1 - t) ^ 3 +
    p1 * 3 * t * (1 - t) ^ 2 +
    p2 * 3 * t ^ 2 * (1 - t) +
    p3 * t ^ 3

Here t is a parametric variable that rannges from 0 to 1.

The following X and Y functions return values of this equation for values of t and the control points' coordinates. Subroutine DrawBezier loops variable t from 0 to 1, uses the functions to generate the points on the Bezier curve, and connects them.

 
' Parametric X function for drawing a degree 3 Bezier curve.
Private Function X(ByVal t As Single, ByVal x0 As Single, _
    ByVal x1 As Single, ByVal x2 As Single, ByVal x3 As _
    Single) As Single
    X = CSng( _
        x0 * (1 - t) ^ 3 + _
        x1 * 3 * t * (1 - t) ^ 2 + _
        x2 * 3 * t ^ 2 * (1 - t) + _
        x3 * t ^ 3 _
        )
End Function

' Parametric Y function for drawing a degree 3 Bezier curve.
Private Function Y(ByVal t As Single, ByVal y0 As Single, _
    ByVal y1 As Single, ByVal y2 As Single, ByVal y3 As _
    Single) As Single
    Y = CSng( _
        y0 * (1 - t) ^ 3 + _
        y1 * 3 * t * (1 - t) ^ 2 + _
        y2 * 3 * t ^ 2 * (1 - t) + _
        y3 * t ^ 3 _
        )
End Function

' Draw the Bezier curve.
Public Sub DrawBezier(ByVal pic As Object, ByVal dt As _
    Single, pt0 As PointF, pt1 As PointF, pt2 As PointF, _
    pt3 As PointF)
    ' Debugging code.
    ' Draw the control lines.
    Dim p As PictureBox
    pic.DrawStyle = vbDot
    pic.Line (pt0.X, pt0.Y)-(pt1.X, pt1.Y)
    pic.Line (pt2.X, pt2.Y)-(pt3.X, pt3.Y)
    pic.DrawStyle = vbSolid

    ' Draw the curve.
    Dim t As Single
    Dim x0 As Single
    Dim y0 As Single
    Dim x1 As Single
    Dim y1 As Single

    t = 0#
    x1 = X(t, pt0.X, pt1.X, pt2.X, pt3.X)
    y1 = Y(t, pt0.Y, pt1.Y, pt2.Y, pt3.Y)
    t = t + dt
    Do While t < 1#
        x0 = x1
        y0 = y1
        x1 = X(t, pt0.X, pt1.X, pt2.X, pt3.X)
        y1 = Y(t, pt0.Y, pt1.Y, pt2.Y, pt3.Y)
        pic.Line (x0, y0)-(x1, y1)
        t = t + dt
    Loop

    ' Connect to the final point.
    t = 1#
    x0 = x1
    y0 = y1
    x1 = X(t, pt0.X, pt1.X, pt2.X, pt3.X)
    y1 = Y(t, pt0.Y, pt1.Y, pt2.Y, pt3.Y)
    pic.Line (x0, y0)-(x1, y1)
End Sub
 
For more information on graphics programming in Visual Basic 6, see my book Visual Basic Graphics Programming.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated