WPF实现图片轮播

一:注意事项:

1 .WPF项目的图片资源,一定要做如下操作

  • .将图片生存操作设置为始终复制

    如果不进行如下设置,本地的图片不会在Image控件中显示

二:使用的技术:

  1. 使用了Thread线程:用来循环更换图片
  2. 使用DoubleAnimation:用来实现图片的淡入和淡出
  3. 使用DispatcherFrame: 实现线程等待

三:核心代码

         /// <summary>
        /// 设置延迟方法
        /// </summary>
        /// <param name="mm"></param>
        public void Delay(int mm)
        {
            DateTime current = DateTime.Now;
            while (current.AddMilliseconds(mm) > DateTime.Now)
            {
                DispatcherHelper.DoEvents();
            }
            return;
        }
/// <summary>
        /// Image的动画效果
        /// </summary>
        public void SetImage()
        {
            DoubleAnimation daV2 = new DoubleAnimation(1, 0, new Duration(TimeSpan.FromSeconds(1)));
            DoubleAnimation daV = new DoubleAnimation(1, 1, new Duration(TimeSpan.FromSeconds(1)));
            Image1.BeginAnimation(UIElement.OpacityProperty, daV2);
            Delay(500);

            Image1.Source = new BitmapImage(new Uri("/Images/" + i + ".png", UriKind.Relative));
            Image1.BeginAnimation(UIElement.OpacityProperty, daV);
            Delay(500);
        }
 /// <summary>
        /// 线程
        /// </summary>
        public void Start()
        {
            while (true)
            {
                if (flag)
                {

                    int num = random.Next(1, 6);
                    if (i == num)
                    {
                        if (num == 5)
                        {
                            num = 1;
                        }
                        else
                        {
                            num += 1;
                        }
                    }
                    i = num;
                    ChangeImage change = new ChangeImage(SetImage);
                    //异步给Image1赋值
                    Image1.Dispatcher.BeginInvoke(change);
                    Delay(1000);
                }
            }
        }

四:效果展示

五:源码地址
源码地址

原文地址:https://www.cnblogs.com/2828sea/p/13371999.html