解决Winform背景图片闪烁的问题
作者:C/S框架网  发布日期:2017/06/22 13:29:40
  解决Winform背景图片闪烁的问题



Winform窗体,里面放置了一个Panel,Dock属性为Fill,BackgroundImage使用一个本地图片文件,
BackgroundImageLayout使用了Stretch。嵌入图片的Panel作为Winform应用程序的背景,这个界面现在有两个问题:
1、在窗体第一次被打开时,背景图片会出现明显的闪烁
2、在拉动窗体的边界以调整窗体大小时,背景图片非出现明显的闪烁

贴图图片

解决方案:

需要新建一个PanelEnhanced类继承Panel类,代码如下:


C# Code:

/// <summary>
/// 加强版 Panel
/// </summary>
class PanelEnhanced : Panel
{
   /// <summary>
   /// OnPaintBackground 事件
   /// </summary>
   /// <param name="e"></param>
   protected override void OnPaintBackground(PaintEventArgs e)
   {
      // 重载基类的背景擦除函数,
      // 解决窗口刷新,放大,图像闪烁
      return;
   }
   
   /// <summary>
   /// OnPaint 事件
   /// </summary>
   /// <param name="e"></param>
   protected override void OnPaint(PaintEventArgs e)
   {
      // 使用双缓冲
      this.DoubleBuffered = true;
      // 背景重绘移动到此
      if (this.BackgroundImage != null)
      {
         e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
         e.Graphics.DrawImage(
         this.BackgroundImage,
         new System.Drawing.Rectangle(0, 0, this.Width, this.Height),
         0,
         0,
         this.BackgroundImage.Width,
         this.BackgroundImage.Height,
         System.Drawing.GraphicsUnit.Pixel);
      }
      base.OnPaint(e);
   }
}

//来源:C/S框架网(www.csframework.com) QQ:1980854898


上一篇 下一篇