Draw an animated atom in C#

[animated atom]

When the form’s Timer fires, its Tick event handler refreshes the form to force a redraw. The form’s Paint event handler draws the atom.

private double Theta = 0;
private const double Dtheta = Math.PI / 5;

// Draw the atom.
private void Form1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.Clear(this.BackColor);
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    Theta += Dtheta;

    const int radius = 3;
    int cx = 50, cy = 50, rx = 45, ry = 15;
    Rectangle rect = new Rectangle(-rx, -ry, 2 * rx, 2 * ry);
    double x, y;
    e.Graphics.RotateTransform(60, MatrixOrder.Append);
    e.Graphics.TranslateTransform(cx, cy, MatrixOrder.Append);
    e.Graphics.DrawEllipse(Pens.Red, rect);
    x = rx * Math.Cos(Theta);
    y = ry * Math.Sin(Theta);
    e.Graphics.FillEllipse(Brushes.Red,
        (int)(x - radius), (int)(y - radius),
        2 * radius, 2 * radius);

    e.Graphics.ResetTransform();
    e.Graphics.RotateTransform(-60, MatrixOrder.Append);
    e.Graphics.TranslateTransform(cx, cy, MatrixOrder.Append);
    e.Graphics.DrawEllipse(Pens.Red, rect);
    x = rx * Math.Cos(-Theta * 0.9);
    y = ry * Math.Sin(-Theta * 0.9);
    e.Graphics.FillEllipse(Brushes.Green,
        (int)(x - radius), (int)(y - radius),
        2 * radius, 2 * radius);

    e.Graphics.ResetTransform();
    e.Graphics.TranslateTransform(cx, cy, MatrixOrder.Append);
    e.Graphics.DrawEllipse(Pens.Red, rect);
    x = rx * Math.Cos(Theta * 0.8);
    y = ry * Math.Sin(Theta * 0.8);
    e.Graphics.FillEllipse(Brushes.Blue,
        (int)(x - radius), (int)(y - radius),
        2 * radius, 2 * radius);

    e.Graphics.ResetTransform();
    e.Graphics.FillEllipse(Brushes.Black,
        cx - radius, cy - radius,
        2 * radius, 2 * radius);
}

For each electron, the Paint event handler uses the Graphics object’s RotateTransform and TranslateTransform methods to prepare to draw rotated and translated objects. It then draws an ellipse centered at the origin. The rotation and scaling position it appropriately for the atom.

Then code then uses trigonometry to figure out where the electron should be on its orbit and draws a circle there.

The angle Theta determines the electrons’ positions. Note that the code multiplies Theta by different values for the different electrons so they move at different speeds.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in animation, drawing, graphics, multimedia and tagged , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *