Чтобы изображение не мерцало при перерисовке, нужно выставить у контрола (в данном случае - у панели) стиль ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer. Пример с двигающимися линиями:
FlickerFreePanel.cs
Код | using System; using System.Collections; using System.Drawing; using System.Windows.Forms;
namespace MyControls { public class FlickerFreePanel : Panel { public FlickerFreePanel() { base.SetStyle(ControlStyles.AllPaintingInWmPaint|ControlStyles.DoubleBuffer, true); }
protected override void OnPaint(PaintEventArgs e) { base.OnPaint (e);
foreach(Rectangle rect in _rects) e.Graphics.DrawLine(Pens.Black, rect.Location, rect.Location+rect.Size); }
// пример
public void AddLine(Rectangle rect) { _rects.Add(rect); this.Refresh(); }
public Rectangle GetLine(int iLine) { return (Rectangle)_rects[iLine]; }
public void MoveLine(int iLine, Rectangle newCoords) { _rects[iLine] = newCoords; this.Refresh(); }
ArrayList _rects = new ArrayList(); } } |
Form1.cs
Код | using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data;
namespace WindowsApplication1 { /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { protected override void OnLoad(EventArgs e) { base.OnLoad (e);
Random rnd = new Random(); for(int i=0; i<10; i++) this.flickerFreePanel1.AddLine(new Rectangle(rnd.Next(150), rnd.Next(150), rnd.Next(150), rnd.Next(150)));
this.timer1.Start(); }
private void timer1_Tick(object sender, System.EventArgs e) { Random rnd = new Random(); for(int i=0; i<10; i++) { Rectangle rect = this.flickerFreePanel1.GetLine(i); int x1 = rect.Left + rnd.Next(3) - 1; int y1 = rect.Top + rnd.Next(3) - 1; int x2 = rect.Right + rnd.Next(3) - 1; int y2 = rect.Bottom + rnd.Next(3) - 1; this.flickerFreePanel1.MoveLine(i, new Rectangle(x1, y1, x2-x1, y2-y1)); } }
private MyControls.FlickerFreePanel flickerFreePanel1; private System.Windows.Forms.Timer timer1;
| |