Winform 实现图片轮播(解决Image.FromFile内存不足) 前言 实现

最近项目中需要在winform中做一个类似于网页那种轮播的效果,这里做下记录。

实现

整体的实现思路如下:

  1. 读取图片文件夹。
  2. 建立一个集合存储Image对象。
  3. 定时器定时更换PictrueBox的显示图片
        private List<Image> ilst = new List<Image>();//全局image集合
        private int imageIndex = 0;//图片索引
        //读取配置文件中的文件夹路径
        private string Slideshow()
        {
            try
            {
                XElement xe = XElement.Load("SettingsConfig.xml");
                string result = xe.Element("imagePath").Value;
                return result;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("文件夹读取失败", ex);//log4net记录
                return null;
            }
        }
        //将读取的image对象添加到集合中
        private void Picture()
        {
            //指定图片类型
            string imgtype = "*.BMP|*.JPG|*.GIF|*.PNG";
            string[] ImageType = imgtype.Split('|');
            for (int i = 0; i < ImageType.Length; i++)
            {
                string[] images = Directory.GetFiles(Slideshow(), ImageType[i]);
                foreach (var item in images)
                {
                    ilst.Add(Image.FromFile(item));
                }
            }            
        }
        //添加一个定时器,图片轮播速度可以通过定时器的Interval属性控制
        private void tmrSlideshow_Tick(object sender, EventArgs e)
        {
            picBacckGround.Image = ilst[imageIndex];
            imageIndex++;
            if (imageIndex > ilst.Count - 1) imageIndex = 0;
        }

        //最后调用Picture方法就可以了 记得把定时器Enable属性设为true。

注意:在测试过程中,出现了Image.FromFile()方法内存不足的错误,指定图片类型就好了。如上面Picture()方法,指定图片类型就可以解决内存不足了。