简体   繁体   中英

Picture Box image flickering

I have a panel containing multiple picturebox.

I want to give users the option of selecting any part of any picturebox.

The user will select it by mouse.

I want to draw a semi-transparent rectangle on the picturebox while the mouse move as per the selection.

The code is working fine, but the rectangle is flickering. I want to stop the flickering.

I tried double buffer using how to stop flickering C# winforms

Also, added Invalide using How to force graphic to be redrawn with the invalidate method

But not working. Please help.

My Code:

private Brush selectionBrush = new SolidBrush(Color.FromArgb(70, 76, 255, 0));

private void Picture_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button != MouseButtons.Left) return;

    PictureBox pb = (PictureBox)(sender);

    Point tempEndPoint = e.Location;
    Rect.Location = new Point(
        Math.Min(RecStartpoint.X, tempEndPoint.X),
        Math.Min(RecStartpoint.Y, tempEndPoint.Y));
    Rect.Size = new Size(
        Math.Abs(RecStartpoint.X - tempEndPoint.X),
        Math.Abs(RecStartpoint.Y - tempEndPoint.Y));

    pb.CreateGraphics().FillRectangle(selectionBrush, Rect);
    pb.Invalidate(Rect);
}

This does not address the PictureBox, but maybe helps.

First I replaced the PictureBox with Panel which can also be used to draw pictures. Next I activated double buffering:

somewhere in the namespace add this class:

class DoubleBufferedPanel : Panel 
{ 
    public DoubleBufferedPanel() : base() 
    { 
        DoubleBuffered = true; 
    } 
 }

and then replace in Form1.Designer.cs all "System.Windows.Forms.Panel" with "DoubleBufferedPanel".

this works fine in many of my graphical applications.

You indicate the Double Buffering solution doesn't work for you, did you find out why? Because the following custom control draws a sizable rectangle on the picturebox without the flicker:

public class TryDoubleBufferAgain : PictureBox
{
    public TryDoubleBufferAgain()
    {
        this.DoubleBuffered = true;
        this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
        this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
        this.UpdateStyles();
    }
    protected override void OnMouseMove(MouseEventArgs e)
    {
        this.Refresh();
        base.OnMouseMove(e);
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);

        // Edit below to actually  draw a usefull rectangle
        e.Graphics.DrawRectangle(System.Drawing.Pens.Red, new System.Drawing.Rectangle(0, 0, Cursor.Position.X, Cursor.Position.Y));
    }
}

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