简体   繁体   中英

Smooth animations in c# Windows Forms

I want to show an animation frame by frame (picture by picture) in a pictureBox. I have 42 frames and I want to make it really fast. I have used the Timer component but interval = 1 milisecond is too slow and I wanted to know if there is any way to make a fast animation with a lot of frames in c# Windows Forms (Visual Studio). This is what I'm using right now

    Bitmap[] FelixBanner = new Bitmap[50];

    public Form1()
    {
        InitializeComponent();

        for(int i = 1; i <= 42; i++)
            FelixBanner[i] = new Bitmap(@"Photos\Felix\" + i + "FB.bmp");
    }

    private void button2_Click(object sender, EventArgs e)
    {
        timer1.Enabled = true;
    }

    int k = 1;

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (k == 41) 
            timer1.Enabled = false;

        Felix.Image = FelixBanner[k];
        k++;
    }

Firstly, none of the built-in timers have 1 ms precision. I do not repeat or copy-paste an older answer of mine but see the link for a high-precision timer. Or see the full source at GitHub .

Secondly, using a PictureBox control for custom rendering is an overkill. Unless you utilize zoom/stretch capabilities, or assign an animated GIF to it, you don't need it at all. It is much more effective to render your animation in a simple Panel , using the Paint event for example. This is how you can do it:

private void timer1_Tick(object sender, EventArgs e)
{        
    if (k == 41) 
        timer1.Enabled = false;

    //Felix.Image = FelixBanner[k];
    k++;
    panelAnimation.Invalidate();
}

void panelAnimation_Paint(object sender, PaintEventArgs e)
{
    // make sure "k" is a valid index even after playing the animation because the
    // Paint event might be called whenever your form is resized or has to be repaint
    var image = FelixBanner[k];
    e.Graphics.DrawImage(image, 0, 0, image.Width, image.Height);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM