Draw an animated hypotrochoid (Spirograph curve) in C#

The example Draw a hypotrochoid (Spirograph curve) in C# shows how to draw a hypothrochoid. This example animates drawing the curve so you can see how the circles trace out the curve's path.

The program uses a Timer with Interval = 100 so it draws a frame every 100 milliseconds or 10 times per second.

The program stores various drawing parameters such as the radii of the circles in form-level variables. It stores the list of points generated so far in the List named points. It stores the current parametric angle in a variable named theta.

// The angle from one circle's center to the other.
private float theta = 0;
private float dtheta;

// Drawing parameters.
private int A, B, C, wid, hgt, cx, cy;
private double max_t;
private List points;

The Timer's Tick event increments theta and calls the DrawCurve method shown in the following code.

// Redraw the curve.
private void tmrDraw_Tick(object sender, EventArgs e)
{
theta += dtheta;
DrawCurve();
}

// Draw the curve.
private void DrawCurve()
{
Bitmap bm = new Bitmap(wid, hgt);
using (Graphics gr = Graphics.FromImage(bm))
{
// Draw the outer circle.
gr.DrawEllipse(Pens.Blue, cx - A, cy - A, 2 * A, 2 * A);

// Draw the inner circle.
int r = A - B;
float cx1 = (float)(cx + r * Math.Cos(theta));
float cy1 = (float)(cy + r * Math.Sin(theta));
gr.DrawEllipse(Pens.Blue, cx1 - B, cy1 - B, 2 * B, 2 * B );

// Add the next point.
PointF new_point = new PointF(
(float)(cx + X(theta, A, B, C)),
(float)(cy + Y(theta, A, B, C)));
points.Add(new_point);

// Draw the line.
gr.DrawLine(Pens.Blue, new PointF(cx1, cy1), new_point);

// Draw the points.
if (points.Count > 1) gr.DrawLines(Pens.Red, points.ToArray());
}

picCanvas.Image = bm;

if (theta > max_t) tmrDraw.Enabled = false;
}

The DrawCurve method creates a new Bitmap. It draws the circles and calculates the next point on the curve. It then draws the line that traces out the path and finally draws the points. The method finishes by displaying the new Bitmap.

  

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
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.