解決Winform背景圖片閃爍的問題
阿新 • • 發佈:2018-12-27
Winform窗體,裡面放置了一個Panel,Dock屬性為Fill,BackgroundImage使用一個本地圖片檔案,
BackgroundImageLayout使用了Stretch。嵌入圖片的Panel作為Winform應用程式的背景,這個介面現在有兩個問題:1、在窗體第一次被開啟時,背景圖片會出現明顯的閃爍2、在拉動窗體的邊界以調整窗體大小時,背景圖片非出現明顯的閃爍
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); } }