c# 播放gif动图
时间: 2023-12-14 10:34:51 浏览: 170
以下是在C#中播放gif动图的示例代码:
```csharp
using System;
using System.Drawing;
using System.Windows.Forms;
namespace GifPlayer
{
public partial class Form1 : Form
{
private Image _gifImage;
private FrameDimension _dimension;
private int _frameCount;
private int _currentFrame;
public Form1()
{
InitializeComponent();
}
private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "GIF files (*.gif)|*.gif";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
_gifImage = Image.FromFile(openFileDialog.FileName);
_dimension = new FrameDimension(_gifImage.FrameDimensionsList[0]);
_frameCount = _gifImage.GetFrameCount(_dimension);
_currentFrame = 0;
timer1.Interval = (int)Math.Round(100 / _gifImage.GetPropertyItem(0x5100).Value[0]) * 10;
timer1.Start();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
_gifImage.SelectActiveFrame(_dimension, _currentFrame);
pictureBox1.Image = _gifImage;
_currentFrame++;
if (_currentFrame == _frameCount)
{
_currentFrame = 0;
}
}
}
}
```
这个示例代码使用了一个计时器来循环播放gif动图。首先,通过打开文件对话框选择一个gif文件,然后获取gif文件的帧数和每一帧的时间间隔。接着,将计时器的间隔设置为每一帧的时间间隔,然后在计时器的Tick事件中选择当前帧并将其显示在PictureBox控件中。最后,将当前帧的索引加1,如果当前帧是最后一帧,则将其重置为第一帧。
阅读全文