繪圖以雙緩衝區避免閃爍

以下編寫的是Windows應用程式

用 OnPaint 進行即時繪圖的

protected override void OnPaint(PaintEventArgs e)

{

        base.OnPaint(e);
        Graphics dc = e.Graphics;
        //以下是繪圖內容

}

由於每秒需要重繪一次圖片,所以出現嚴重的閃爍問題。

主要有3中解決方法

1. 將Form的DoubleBuffered屬性設置為true。

改變這個屬性後,重繪閃爍問題依然存在。

2. 在構造函數中增加改變控制項屬性的代碼

public From1_From()
{
        InitializeComponent();

   
        // 修改屬性代碼

        SetStyle(ControlStyles.UserPaint, true);
        SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
        SetStyle(ControlStyles.DoubleBuffer, true); // 雙緩衝
        this.UpdateStyles();
}

增加代碼後,重繪閃爍問題依然存在。

3. 先將圖形繪製到bitmap圖片中,在載入這個圖片

protected override void OnPaint(PaintEventArgs e)

{

        base.OnPaint(e);
        Graphics g = e.Graphics;

        //注意,這裡千萬不可用Graphics g = this.CreateGraphics() 獲得繪圖變數。否則閃爍將非常厲害。

        Bitmap b = new Bitmap(this.Width, this.Height);
        Graphics dc = Graphics.FromImage((System.Drawing.Image)b);

        //將要繪製的內容繪製到dc上

        g.DrawImage(b, 0, 0);
        dc.Dispose();

}

使用這種方法後,重繪閃爍問題得到很好的解決,推薦使用這種方法。

http://blog.csdn.net/daming_ocean/article/details/...

陳鍾誠 (2012年11月27日),(網頁標題) C# 繪圖,以雙緩衝區避免閃爍,(網站標題) 免費電子書:C# 程式設計,2012年11月27日,取自 http://cs0.wikidot.com/doublebuffering ,網頁修改第 1 版。

arrow
arrow

    Johnson峰 發表在 痞客邦 留言(0) 人氣()