【问题标题】:Picture Box image flickering图片框图像闪烁
【发布时间】:2017-05-18 06:35:29
【问题描述】:

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

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

用户将通过鼠标选择它。

我想在图片框上绘制一个半透明的矩形,同时鼠标根据选择移动。

代码运行正常,但矩形闪烁。 我想停止闪烁。

我尝试使用 how to stop flickering C# winforms 进行双缓冲

另外,使用How to force graphic to be redrawn with the invalidate method添加了无效

但不工作。请帮忙。

我的代码:

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

【问题讨论】:

  • 如果你删除pb.Invalidate(Rect);会怎样
  • @LeiYang 绘制的矩形没有透明度,鼠标上移也不会消失。
  • 我猜你需要在Paint事件中绘制全部/部分,这样你就可以在其他按钮事件中调用Invalidate
  • 最好在 Paint handler 中进行绘画作品。你应该改变你的方法。
  • 你昨天问的那个问题呢?我在MouseUp 上给你example how to clear rectangle 的那个?在有人给你写申请之前,你会一直问问题吗?

标签: c# image winforms visual-studio picturebox


【解决方案1】:

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

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

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

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

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

这在我的许多图形应用程序中都能正常工作。

【讨论】:

    【解决方案2】:

    您表示双缓冲解决方案对您不起作用,您找到原因了吗?因为下面的自定义控件在图片框上绘制了一个相当大的矩形而没有闪烁:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-27
      • 2021-02-09
      • 1970-01-01
      • 2012-08-22
      • 2015-04-25
      • 2012-05-13
      • 2010-10-29
      • 1970-01-01
      相关资源
      最近更新 更多