简体   繁体   中英

C# redraw blinking

I have UserControl : Panel. When I add to Form own UserControl. UserControl.Anchor = Left|Right|Top|Bottom. When I resize Form Rectangle is blinking. How can you make that do not blink?

public partial class UserControl1 : Panel
{
    public UserControl1()
    {
        InitializeComponent();
        this.ResizeRedraw = true;
    }

    private void UserControl1_Paint(object sender, PaintEventArgs e)
    {
        using (Graphics g = this.CreateGraphics())
        {
            Pen pen = new Pen(Color.Black, 1);
            Brush brush = new SolidBrush(Color.Black);

            g.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1);

            pen.Dispose();
        }
    }
}

There are many things you can do to reduce flicker:

  • make your paint handler as fast as possible by moving unnecessary work out of the method (eg create brushes and pens outside the method and cache them to avoid the creation cost on every paint; clear the background using gfx.Clear rather than filling the rectangle; redesign your display so you don't have to draw so much stuff; cache parts of the image in bitmaps so they can be redrawn faster)
  • avoid drawing each pixel more than once (if you fill the background with white and then draw over it with black, it will flicker. But if you draw awhite rectangle and then draw a frame around it in black you can avoid the flicker)
  • only draw the visible part of your graphics by checking the clip rectangle, to avoid the work of drawing stuff that isn't currently visible)
  • ensure that the framework is not filling the background for you (usually in white) by overriding the erase background handling.
  • enable double buffering so that any remaining flicker is eliminated. This uses a lot more resources than the other approaches, although these days that's not usually much of a problem.
  • use red existing e.Graphics to draw with rather than calling CreateGraphics

Try set doubleBuffered = true and you do not have to create graphics object in pain event. you can get that from the event args. You have to make sure you do minimum amount of task in a paint event.

public partial class UserControl1 : Panel
{
    public UserControl1()
    {
        InitializeComponent();
        this.ResizeRedraw = true;
        this.DoubleBuffered = true;
    }

    private void UserControl1_Paint(object sender, PaintEventArgs e)
    {
        var g = e.Graphics;
        Pen pen = new Pen(Color.Black, 1);
        Brush brush = new SolidBrush(Color.Black);
        g.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM