图片框图像闪烁

时间:2017-05-18 06:35:29

标签: c# image winforms visual-studio picturebox

我有一个包含多个图片框的面板。

我想让用户选择任何图片框的任何部分。

用户将通过鼠标选择它。

我希望在图片框上绘制一个半透明的矩形,同时按照选择移动鼠标。

代码工作正常,但矩形闪烁。 我想停止闪烁。

我使用how to stop flickering C# winforms

尝试了双缓冲

此外,使用How to force graphic to be redrawn with the invalidate method

添加了Invalide

但不行。请帮忙。

我的代码:

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);
}

2 个答案:

答案 0 :(得分:1)

这不能解决 PictureBox,但可能有帮助。

首先我用Panel替换了PictureBox,Panel也可以用来画图。接下来我激活了双缓冲:

在命名空间的某处添加这个类:

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

然后替换 Form1.Designer.cs 所有“System.Windows.Forms.Panel”和“DoubleBufferedPanel”。

这在我的许多图形应用程序中都运行良好。

答案 1 :(得分:0)

您指出Double Buffering解决方案不适合您,您是否找到了原因?因为以下自定义控件在图片框上绘制了一个相当大的矩形而没有闪烁:

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));
    }
}
相关问题