You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Windows Forms中创建可播放动图的控件?现有代码仅显示最后一帧

GIF动图仅显示最后一帧,无法逐帧播放的问题

我尝试实现了一个自定义控件播放GIF,但控件仅显示GIF的最后一帧;将FrameDelay设置为1000毫秒时,会先等待1秒再显示最后一帧,无法从第一帧到最后一帧逐帧播放。使用PictureBox加载该动图,也出现了相同的问题。

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

public class AnimatedGifControl : Control
{
    private List<Image> frames;
    private int currentFrameIndex;
    private Timer animationTimer;

    [Browsable(true)]
    [Category("Behavior")]
    [Description("The delay between frames in milliseconds.")]
    public int FrameDelay { get; set; } = 100; // Default frame delay

    public AnimatedGifControl()
    {
        frames = new List<Image>();
        DoubleBuffered = true;
        animationTimer = new Timer();
        animationTimer.Tick += OnAnimationTick;
    }

    public void LoadGif(string gifPath)
    {
        frames.Clear();
        using (Image gifImage = Image.FromFile(gifPath))
        {
            int frameCount = gifImage.GetFrameCount(FrameDimension.Time);
            for (int i = 0; i < frameCount; i++)
            {
                gifImage.SelectActiveFrame(FrameDimension.Time, i);
                frames.Add(new Bitmap(gifImage));
            }
        }

        currentFrameIndex = 0;
        if (frames.Count > 0)
        {
            animationTimer.Interval = FrameDelay;
            animationTimer.Start();
        }
    }

    private void OnAnimationTick(object sender, EventArgs e)
    {
        currentFrameIndex = (currentFrameIndex + 1) % frames.Count;
        Invalidate();
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        if (frames.Count > 0)
        {
            e.Graphics.DrawImage(frames[currentFrameIndex], 0, 0, Width, Height);
        }
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            animationTimer.Dispose();
            foreach (var frame in frames)
            {
                frame.Dispose();
            }
        }
        base.Dispose(disposing);
    }
}

内容的提问来源于stack exchange,提问作者Daniel Lip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 18:33:13