在winForm中实现图片闪烁效果代码

时间:2021-05-22 19:45:13

       启用一个线程来处理此功能。

        /// <summary>     

         /// 将指定图片控件中的图片闪烁
        /// </summary>
        /// <param name="pic">需要闪烁的图片控件</param>
        public static void FlashImage(object picBox)
        {
            PictureBox pic = picBox as PictureBox;
            if (pic == null)
                Thread.CurrentThread.Abort();

            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
            //跨线程调用,.NET Framework 2.0会出现这个问题,可以在创建控件的基础句柄所在线程上异步执行指定委托
          
            Bitmap bmp = new Bitmap(23, 23);//大小视情况而定,不要影响到界面其他地方
            Graphics gph;
            //从指定的Image对象创建新Graphics对象
            Color colorTouMing = Color.FromArgb(0, 240, 240, 240);//透明颜色
            gph = Graphics.FromImage(bmp);
            Bitmap mybit = new Bitmap(pic.Image); //需要闪烁的PictureBox控件图片        
            while (true)
            {
                gph.Clear(colorTouMing);
                gph.DrawImage(mybit, 0, 1, 20, 20);
                pic.Image = bmp;//接受到消息,图片跳动
                Thread.Sleep(300);

                gph.Clear(colorTouMing);
                gph.DrawImage(mybit, 1, 0, 23, 23);
                pic.Image = bmp;//接受到消息,图片跳动
                Thread.Sleep(300);

                gph.Clear(colorTouMing);
                gph.DrawImage(mybit, 1, 1, 20, 20);
                pic.Image = bmp;//接受到消息,图片跳动
                Thread.Sleep(300);

                gph.Clear(colorTouMing);
                gph.DrawImage(mybit, 1, 0, 23, 23);
                pic.Image = bmp;//接受到消息,图片跳动
                Thread.Sleep(300);
            }
        }