【发布时间】:2013-03-03 13:11:40
【问题描述】:
考虑以下绘制函数(缩写):
public void paint(object sender, PaintEventArgs e)
{
base.OnPaint(e);
Graphics g = e.Graphics;
BufferedGraphicsContext context = BufferedGraphicsManager.Current;
BufferedGraphics buffer = context.Allocate(g, e.ClipRectangle);
buffer.Graphics.Clear(Color.PaleVioletRed);
// skip drawing if cond is true (condition is not relevant)
if(!cond)
{
try
{
// l is some List<p>
foreach(Point p in l)
{
// ...calculate X and Y... (not relevant)
buffer.Graphics.FillEllipse(new SolidBrush(Color.Blue), p.X,p.Y, Point.SIZE,Point.SIZE);
}
}
catch {} // some exception handling (not relevant)
finally{
buffer.Render(g);
}
}
buffer.Render(g);
}
请注意,上面的代码或多或少是伪代码。我希望使用 BufferedGraphics 对象,闪烁会消失。事实上,它没有。起初,我认为paint-method 会花费很长时间,但它可能不会(我测量了每次调用 4-7 毫秒)。如果我将cond 设置为true,它仍然会闪烁,尽管paint-method 几乎不需要时间。绘画方法将在面板上绘画并且我使用计时器大约每 50 毫秒使面板无效可能很重要。我怎样才能最终消除闪烁?
【问题讨论】:
-
终于需要了吗?无论如何,您都在渲染。
-
谢谢,真的不需要。但是,问题依然存在。
-
您的代码没有消除闪烁的主要原因,即由 OnPaintBackground() 完成的绘图。支持 Winforms 中对双缓冲的内置支持。检查this answer 以获得双缓冲面板。或者,如果您不需要滚动支持,则只需使用 PictureBox,这是默认打开双缓冲的最基本控件。
-
感谢您对 PictureBox 的提示!
标签: c# doublebuffered