【问题标题】:Double buffering doesn't work on a panel?双缓冲在面板上不起作用?
【发布时间】:2013-03-05 06:25:22
【问题描述】:

我正在开发一个类似于 ms paint 的小型绘画程序。目前,我正在尝试实现“选择功能”。我正面临闪烁的问题,所以我做了一些研究,发现我应该创建自己的 Panel 类。

public class MyDisplay : Panel
    {   
        public MyDisplay()
        {
            this.DoubleBuffered = true;            

            this.SetStyle(ControlStyles.UserPaint |
              ControlStyles.AllPaintingInWmPaint |
              ControlStyles.ResizeRedraw |
              ControlStyles.ContainerControl |
              ControlStyles.OptimizedDoubleBuffer |
              ControlStyles.SupportsTransparentBackColor
              , true);

            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            this.UpdateStyles();
        }
    }

在主窗体中有字段:

MyDisplay panel1 = new MyDisplay();
Graphics graphics1 = panel1.CreateGraphics();

我在面板上使用 3 个事件:

  1. MouseDown - 我到了 P1 点
  2. MouseMove - 这就是我遇到闪烁问题的地方,我正在调用 graphics1.drawRectangle(...)graphics1.Clear() 每次点击鼠标都会移动
  3. MouseUp - 我只是最后一次绘制矩形。

这有什么问题?为什么即使整个面板是白色的并且那里只有 1 个矩形,我仍然会遇到闪烁问题?谢谢。

编辑:

我已经覆盖了 OnPaint 方法,但我仍然不知道下一步该做什么。

   protected override void OnPaint(PaintEventArgs e)
    {
        // Call the OnPaint method of the base class.
        base.OnPaint(e);
        // Call methods of the System.Drawing.Graphics object.
        e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle);
    } 

编辑2: 我应该在位图/图像上绘画并覆盖 OnPaint 方法以从那里复制图像并将其粘贴到面板吗?

【问题讨论】:

  • 您正在使用 CreateGraphics() 破坏双缓冲功能。您必须重写 OnPaint() 方法来进行绘画并避免闪烁。
  • 你介意给我一些关于使用 OnPaint 的提示吗?我不知道它应该如何工作,我一直试图在谷歌上找到它,但没有结果

标签: c# graphics doublebuffered


【解决方案1】:

删除定义 graphics1 字段的行。

使用通过 PaintEventArgs 对象传入的 Graphics 对象在 OnPaint 的覆盖中执行所有绘制。使用方法 Invalidate()、Refresh() 和 Update() 来控制从其他代码重绘的时间。

如果您在此设计中遇到任何特定困难,请回调。

【讨论】:

  • 你能给我举个例子吗?我不确定它应该是什么样子,如果我想绘制矩形和圆形,我应该在 OnPaint 中放置其中的 2 个方法吗?
  • 我应该在位图/图像上绘画并重写 OnPaint 方法以从那里复制图像并将其粘贴到面板吗?
  • 在位图上绘制和将位图绘制到屏幕上,通常都是通过 OnPaint 方法完成的。
猜你喜欢
  • 2011-11-26
  • 2011-01-05
  • 2012-07-29
  • 2013-10-20
  • 2010-10-23
  • 2021-04-28
  • 2014-03-29
  • 2020-04-01
  • 2015-08-02
相关资源
最近更新 更多