解决双缓冲的关键技术:
1、设置显示图元控件的几个属性:必须要设置,否则效果不是很明显!
this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint, true);
2、窗口刷新一次的过程中,让所有图元同时显示到窗口。可以通过以下几种方式实现,这几种方式都涉及到Graphics对象的创建方式。
a、在内存上创建一块和显示控件相同大小的画布,在这块画布上创建Graphics对象。接着所有的图元都在这块画布上绘制,绘制完成以后再使用该画布覆盖显示控件的背景,从而达到“显示一次仅刷新一次”的效果!实现代码(在OnPaint方法中):
- Rectangle rect = e.ClipRectangle;
- Bitmap bufferp_w_picpath = new Bitmap(this.Width, this.Height);
- Graphics g = Graphics.FromImage(bufferp_w_picpath);
- g.Clear(this.BackColor);
- g.SmoothingMode = SmoothingMode.HighQuality; //高质量
- g.PixelOffsetMode = PixelOffsetMode.HighQuality; //高像素偏移质量
- foreach (IShape drawobject in doc.drawObjectList)
- {
- if (rect.IntersectsWith(drawobject.Rect))
- {
- drawobject.Draw(g);
- if (drawobject.TrackerState == config.Module.Core.TrackerState.Selected && this.CurrentOperator ==Enum.Operator.Transfrom) //仅当编辑节点操作时显示图元热点
- {
- drawobject.DrawTracker(g);
- }
- }
- }
- using (Graphics tg = e.Graphics)
- {
- tg.DrawImage(bufferp_w_picpath, 0, 0); //把画布贴到画面上
- }
b、直接在内存上创建Graphics对象:
- Rectangle rect = e.ClipRectangle;
- BufferedGraphicsContext currentContext = BufferedGraphicsManager.Current;
- BufferedGraphics myBuffer = currentContext.Allocate(e.Graphics, e.ClipRectangle);
- Graphics g = myBuffer.Graphics;
- g.SmoothingMode = SmoothingMode.HighQuality;
- g.PixelOffsetMode = PixelOffsetMode.HighSpeed;
- g.Clear(this.BackColor);
- foreach (IShape drawobject in doc.drawObjectList)
- {
- if (rect.IntersectsWith(drawobject.Rect))
- {
- drawobject.Draw(g);
- if (drawobject.TrackerState == config.Module.Core.TrackerState.Selected && this.CurrentOperator ==Enum.Operator.Transfrom)//仅当编辑节点操作时显示图元热点
- {
- drawobject.DrawTracker(g);
- }
- }
- }
- myBuffer.Render(e.Graphics);
- g.Dispose();
- myBuffer.Dispose();//释放资源