Draw a hypotrochoid (Spirograph curve) in C#

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:

// The parametric function X(t).
private double X(double t, double A, double B, double C)
{
return (A - B ) * Math.Cos(t) + C * Math.Cos((A - B ) / B * t);
}

// The parametric function Y(t).
private double Y(double t, double A, double B, double C)
{
return (A - B ) * Math.Sin(t) - C * Math.Sin((A - B ) / B * t);
}

To trace the entire curve, the variable t must vary from 0 to 2 * Pi * B / GCD(A, B ). For information on calculating the GCD (Greatest Common Divisor), see Calculate the greatest common divisor (GCD) and least common multiple (LCM) of two integers in C#.

The program uses the following code to draw the complete curve when you enter parameters and click Draw. The iter parameter determines how many points the program uses. Bigger values give smoother results, although using very small values can be interesting, too.

// Draw the hypotrochoid.
private void btnDraw_Click(object sender, EventArgs e)
{
int A = int.Parse(txtA.Text);
int B = int.Parse(txtB.Text);
int C = int.Parse(txtC.Text);
int iter = int.Parse(txtIter.Text);

int wid = picCanvas.ClientSize.Width;
int hgt = picCanvas.ClientSize.Height;
Bitmap bm = new Bitmap(wid, hgt);
using (Graphics gr = Graphics.FromImage(bm))
{
int cx = wid / 2;
int cy = hgt / 2;
double t = 0;
double dt = Math.PI / iter;
double max_t = 2 * Math.PI * B / GCD(A, B );
double x1 = cx + X(t, A, B, C);
double y1 = cy + Y(t, A, B, C);
while (t <= max_t)
{
double x0 = x1;
double y0 = y1;
t += dt;
x1 = cx + X(t, A, B, C);
y1 = cy + Y(t, A, B, C);
gr.DrawLine(Pens.Black, (float)x0, (float)y0, (float)x1, (float)y1);
}
}

picCanvas.Image = bm;
}

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.