[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Draw an animated atom in C#

[Draw an animated atom in C#]

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.