Use transformations to draw an animated atom in C#

When the form's Timer fires, the 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.

   

 

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.