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

Title Draw an hypotrochoid (and hypocycloid) in VB .NET This example shows how to draw an hypotrochoid (and hypocycloid) in VB .NET. hypotrochoid, hypocycloid, curve VB.NET, Graphics

The hypotrochoid is a curve drawn by rolling a circle (of radius B) around the inside circumference of another (of radius A). A point attached to the inner circle and distance C from its center draws the curve.

You can draw an hypotrochoid with the following parametric functions:

Private Function X(ByVal t As Single) As Single
Return (m_A - m_B) * Cos(t) + m_C * Cos(t * (m_A - m_B) _
/ m_B)
End Function

Private Function Y(ByVal t As Single) As Single
Return (m_A - m_B) * Sin(t) - m_C * Sin(t * (m_A - m_B) _
/ m_B)
End Function

Here the variable t ranges from 0 to m_B / GCD(m_A, m_B) * 2 * Pi. The program uses the following code to draw the complete curve when the form needs to be refreshed.

Private Sub DrawCurve(ByVal gr As Graphics, ByVal xmin As _
Integer, ByVal ymin As Integer, ByVal xmax As Integer, _
ByVal ymax As Integer)
If Not m_FormLoaded Then Exit Sub

' Get A, B, C, and num_segments.
m_A = Integer.Parse(txtA.Text)
m_B = Integer.Parse(txtB.Text)
m_C = Single.Parse(txtC.Text)
Dim num_segments = Integer.Parse(txtNumSegs.Text)

' Scale and translate to center the drawing.
Dim r As Single = m_A - m_B + m_C
MapGraphicsWindow(gr, -r, -r, r, r, _
xmin, ymin, xmax, ymax)

' Clear the canvas.
gr.Clear(picCanvas.BackColor)

' Draw the geometry for debugging.
If chkShowGeometry.Checked Then
Dim red_pen As New Pen(Color.Red, 0)
gr.DrawEllipse(red_pen, -m_A, -m_A, 2 * m_A, 2 * _
m_A)
gr.DrawEllipse(red_pen, m_A - 2 * m_B, -m_B, 2 * _
m_B, 2 * m_B)
gr.DrawLine(red_pen, m_A - m_B, 0, m_A - m_B + m_C, _
0)
red_pen.Dispose()
End If

Dim num_revs As Integer = m_B / GCD(m_A, m_B)
Dim dt As Single = num_revs * 2 * PI / num_segments
Dim t As Single = 0
Dim x1, y1, x2, y2 As Single
Dim i As Integer
Dim thin_pen As New Pen(Color.Blue, 0)

' Draw the curve.
x2 = X(0)
y2 = Y(0)
For i = 1 To num_segments
t += dt
x1 = x2
y1 = y2
x2 = X(t)
y2 = Y(t)
gr.DrawLine(thin_pen, x1, y1, x2, y2)
Next i

x1 = X(0)
y1 = Y(0)
gr.DrawLine(thin_pen, x1, y1, x2, y2)

thin_pen.Dispose()
End Sub

' Return the greatest common divisor of A and B.
Private Function GCD(ByVal A As Integer, ByVal B As _
Integer) As Integer
Dim R As Integer = A Mod B
If R = 0 Then
Return B
Else
Return GCD(B, R)
End If
End Function

Special cases of the hypotrochoid include:

• The hypocycloid where C = B.
• A rose where:
A = 2 * N * C / (N + 1)
B = (N - 1) * C / (N + 1)
for integer values of N.

For more information on graphics programming in Visual Basic (VB 6), see my book Ready-to-Run Visual Basic Graphics Programming.