WinForm里加载GIF图片

    项目需要添加加载页面,比如点击一条数据,然后点击预览按钮,这时候会弹出页面,首先显示一个加载信息  一张GIF图片,后面跟文字:“正在生成预览,请稍后..”之类的,实际上是正在与后台交互。再得到返回数据以后,隐藏掉加载信息,显示数据内容。参考了一些例子,做的时候还是遇到问题,解决以后记录一下,给其他有需要的朋友们。

    在Form里有DataGridView负责显示数据,下面有Button负责操作,然后再向From中添加一个panel负责加载信息,最后添加的panel在最上层,初始化的时候panel.Dock = Dock.Fill;在panel中画一个gif图片并显示“正在生成预览,请稍后...”字样。

 

首先,类中添加引用:

using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;


声明类变量,两个Thread和一个结束查询后关闭加载信息的委托:

private System.Threading.Thread queryThread;
private System.Threading.Thread gifThread;
//<summary>查询结束后关掉加载信息的委托</summary>
private delegate void EndQuery();

注意要加上前面的  System.Threading

 

然后在窗体加载的方法里做一些初始化:

private void Form_Load(object sender,EventArgs e)
{
    this.queryThread = new System.Threading.Thread(queryDate);
    this.queryThread.IsBackground=true;
    this.queryThread.Start();

    this.gifThread = new System.Threading.Thread(DisplayGIF);
    this.gifThread.IsBackground = true;
    this.gifThread.Start();
}


接下来实现方法,queryDate()方法就是与后台服务器进行交互查询数据,查询结束以后要关掉查询线程并显示界面。

private void queryDate()
{
    //Connect To Server


    //查询结束以后要结束掉预览界面
    this.Invoke(new EndQuery(EndQueryMethod));
}



委托的EndQueryMethod()负责关掉线程。

private void EndQueryMethod()
{
    this.panel1.Visible = false;
    try{
        this.queryThread.Abort();
        this.gifThread.Abort();
   }catch{
        //do nothing
    }
}


 

DisplayGIF()方法负责显示GIF

private void DisplayGIF()
{
            Bitmap adimatedGif = new Bitmap(@"C:\GIF\2.gif");//这里貌似只能给路径,我写 Properties.Resource._2  会报错。
            Graphics g = this.panel1.CreateGraphics();
            int PropertyTagFrameDelay = 0x5100;
            PropertyItem propItem = adimatedGif.GetPropertyItem(PropertyTagFrameDelay);
            byte[] bites = propItem.Value;
            FrameDimension frameDimension = new FrameDimension(adimatedGif.FrameDimensionsList[0]);
            int frameCount = adimatedGif.GetFrameCount(FrameDimension.Time);
            int[] delays = new int[frameCount + 1];
            int i = 0;
            for (i = 0; i <= frameCount - 1; i++)
            {
                delays[i] = BitConverter.ToInt32(bites, i * 4);
            }
            while (true)
            {
                for (i = 0; i <= adimatedGif.GetFrameCount(frameDimension) - 1; i++)
                {
                    adimatedGif.SelectActiveFrame(frameDimension, i);
                    g.DrawImage(adimatedGif, new Point(100, 100));
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(delays[i] * 10);
                }
            }
}


以上,欢迎各路大神批评指正,多多留言~

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值