Animation is result of redrawing your model in an interval; and in each interval applying some changes, like change of the color for a blink effect, or change of location or size for a move or grow or shrink effect.
In a loading example like what you shared in your question, the animation is result of changing the active circle in the interval and drawing active circle with different color. So, you need a timer, set the interval and in the timer increment the active circle index and call Invalidate to raise paint. Then in the paint event, draw all circles, but the one which is active, should be in different color. In the next interval, active index will move, and after a redraw it looks like the active circle is moving:
Here is the code:
using System;
using System.Drawing;
using System.Windows.Forms;
public class LoadingDotsControl : Control
{
private Timer timer;
public LoadingDotsControl()
{
timer = new Timer();
timer.Interval = 300;
timer.Tick += Timer_Tick;
timer.Enabled = true;
DoubleBuffered = true;
ResizeRedraw = true;
}
int count = 5;
int active = 0;
private void Timer_Tick(object sender, EventArgs e)
{
Invalidate();
active = (active + 1) % count;
}
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.Clear(BackColor);
e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
var w = this.Width / count;
var h = this.Height / 2;
var padding = w / 8;
for (int i = 0; i < count; i++)
{
var rect = new Rectangle(i * w, h - w / 2, w, w);
var brush = active == i? Brushes.RoyalBlue: Brushes.SkyBlue;
rect.Inflate(-padding, -padding);
e.Graphics.FillEllipse(brush, rect);
}
base.OnPaint(e);
}
protected override void Dispose(bool disposing)
{
if (disposing && (timer != null))
{
timer.Dispose();
}
base.Dispose(disposing);
}
}
If you want to see more examples, take a look at my post here:
- Show Transparent Loading Spinner above other Controls
- Show Loading animation during loading data in other thread which simply uses a gif animation for loading.