Domanda

I'm trying to do double buffering to get rid of the flicker, but redrawing the image flickers. I need to redraw the image with a periodicity in the bar at a new location, it works for me. But when redrawing very noticeable flicker. Help please.

namespace CockroachRunning
{
    public partial class Form1 : Form
    {
        Random R = new Random();
        Semaphore s1 = new Semaphore(2, 4);
        Bitmap cockroachBmp = new Bitmap(Properties.Resources.cockroach, new Size(55, 50));
        List<Point> cockroaches = new List<Point>();
        public Form1()
        {
            InitializeComponent();
            this.DoubleBuffered = true;
            cockroaches.Add(new Point(18,13));
            Thread t1 = new Thread(Up);
            t1.Start();
        }
        public void Up()
        {
            while (true) 
            {
                s1.WaitOne();
                int distance = R.Next(1, 6);
                for (int i = 0; i < distance; i++)
                {
                    if (cockroaches[0].Y - 1 > -1)
                    {
                        cockroaches[0] = new Point(cockroaches[0].X, cockroaches[0].Y - 1);
                        panel1.Invalidate();                        
                    }
                }
                s1.Release();
                Thread.Sleep(100);
            }
        }
        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            Image i = new Bitmap(panel1.ClientRectangle.Width, panel1.ClientRectangle.Height);
            Graphics g = Graphics.FromImage(i);
            Graphics displayGraphics = e.Graphics;
            g.DrawImage(cockroachBmp, cockroaches[0]);
            displayGraphics.DrawImage(i, panel1.ClientRectangle);
        }
    }
}
È stato utile?

Soluzione

To get rid of flickering, I use the following settings to configure how a control behaves:

base.DoubleBuffered = true;

SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
UpdateStyles();

I call this in the constructor of a Control-derived class. I'm not sure whether this also works for forms, too, but I would imagine that it does.

The drawing is then done in void OnPaintBackground(PaintEventArgs e) (erasing the client area) and void OnPaint(PaintEventArgs e) (actual drawing).

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top