缓冲图形闪烁

本文关键字:闪烁 图形 缓冲 | 更新日期: 2023-09-27 17:56:26

我尝试实现自定义双缓冲,但它会导致闪烁。

这是控件(从控件继承的自定义控件)构造函数中的代码:

bufferContext = new BufferedGraphicsContext();
SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
SetStyle(ControlStyles.DoubleBuffer, false);
SetStyle(ControlStyles.ResizeRedraw, false);
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
SetStyle(ControlStyles.Opaque, true);

上漆事件:

protected override void OnPaint(PaintEventArgs e)
{
    if (buffer == null)
    {
        Draw(e);
        return;
    }
    if (Repaint)
    {
        Repaint = false;
        PaintEventArgs pe = new PaintEventArgs(buffer.Graphics, e.ClipRectangle);
        Draw(pe);
    }
    buffer.Render(e.Graphics);
}

此外,此代码在调整与缓冲相关的大小时激活:

Graphics g = this.CreateGraphics();
if (buffer != null)
{
    buffer.Dispose();
    buffer = null;
}
if (!(bufferContext == null || DisplayRectangle.Width <= 0 || DisplayRectangle.Height <= 0))
{
    buffer = bufferContext.Allocate(g, DisplayRectangle);
    Repaint = true;
}

绘制方法很复杂,但它首先用 BackColor 填充控件,其他则无关紧要。

我可以用眼睛发现有时会闪烁,主要是在调整窗口大小时。正如我所感知的那样,黑色首先被涂成控制,然后是缓冲区中的图形,它会导致闪烁。但是,背景色从来都不是黑色的。

如何阻止这种情况?

缓冲图形闪烁

此示例演示如何正确使用缓冲图形:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GDI_PAINTING_EXAMPLE
{
    public class PaintingExample : Control
    {
        public Graphics G;
        public Bitmap Frame = new Bitmap(256, 256);
        public Bitmap Buffer = new Bitmap(256, 256);
        public PaintingExample()
        {
            // Create a new Graphics instance.
            G = Graphics.FromImage(Buffer);
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            // Clears Buffer To White
            G.Clear(Color.White);

            //
            // Do Your Painting Routine
            //
            //
            // End Your Painting Routine
            //

            // Set Frame to draw as Buffer
            Frame = Buffer;
            // Draw Frame with Paint Event Graphics as one image.
            e.Graphics.DrawImage(Frame, new Point(0, 0));
        }
        protected override void OnPaintBackground(PaintEventArgs pevent)
        {
        }
    }
}