So I'm attempting to make some animations with Winforms
, and more specifically, a left to right animation. However, I've ran into multiple problems.
Firstly, the System.Windows.Forms.Timer
and even the other Timer classes like System.Threading.Timer
are not nearly fast enough for the animation I want. To compensate, I could increase the amount of pixels by which I add to the left right animation. However, this results in a choppy-animation, which is not what I'm going for. To fix this, I'm using my own timer (on another thread), which is much more accurate:
long frequency = Stopwatch.Frequency;
long prevTicks = 0;
while (true)
{
double interval = ((double)frequency) / Interval;
long ticks = Stopwatch.GetTimestamp();
if (ticks >= prevTicks + interval)
{
prevTicks = ticks;
Tick?.Invoke(this, EventArgs.Empty);
}
}
This however has its own drawbacks. First, this puts a heavy load on the CPU. Secondly, I cannot redraw fast enough if I want to increase the left-right animation by 1 pixel at a time for a smooth animation. The solution to this is to directly draw on the graphics provided by CreateGraphics
, and it works fairly well, except when we go to transparent brushes. Then, things slow down.
The solution to all of this is to just increase the amount of pixels I draw at a time on the left-right animation, but this would result in a lack of smoothness for the animation. Here is some test code:
private int index;
private Graphics g;
private Brush brush;
private void FastTimer_Tick(object sender, EventArgs e)
{
index++;
if (g == null)
{
g = CreateGraphics();
}
if (brush == null)
{
brush = new SolidBrush(Color.FromArgb(120, Color.Black));
}
g.FillRectangle(brush, index, 0, 1, Height);
}
I've heard the GDI
is much faster as it's hardware accelerated, but I'm not sure how to use it.
Does anybody have a solution to this while sticking to winforms
? Thanks.
EDIT: Here's an example video: https://www.youtube.com/watch?v=gcOttFFCUz8&feature=youtu.be When the form is minimized, it's very smooth. However, when the form is maximized, I have to compensate smoothness for speed. I'm looking to know how to redraw faster (possibly using GDI) so that I can still use +1px animations, for a smooth experience.