要实现局部刷新,我们就必须调用onpaint方法,但是如果用refresh那么就是全局刷新,这样很影响效率。
但是局部刷新怎么办?那就要用到区域的失效,我们迫使窗体的一个区域失效(Invalidate(region or rectangle)
,调用系统的onapint函数,
系统就会刷新失效的区域。这样就可以做到局部刷新了。
一般情况下,如果你调用了invalidate方法,系统会在满足条件的情况下刷新区域,但是我们也可以强制进行调用
onpaint函数,就是this.Uptate();
一下是代码:有三个区域rectangle,分别画不同的图形。
- public partial class Form1 : Form
- {
- Rectangle rect1;
- Rectangle rect2;
- Rectangle rect3;
- Timer timer;
- public Form1()
- {
- InitializeComponent();
- rect1 = new Rectangle(10, 10, 200, 20);
- rect2 = new Rectangle(350, 50, 100, 20);
- rect3 = new Rectangle(10, 70, 50, 50);
- timer = new Timer();
- timer.Enabled = true;
- timer.Interval = 500;
- timer.Tick += new EventHandler(Timer_Tick);
- }
- private void Timer_Tick(object sender, EventArgs e)
- {
- Graphics g = this.CreateGraphics();
- draw(g);
- }
- private void draw(Graphics g)
- {
- g.SetClip(this.ClientRectangle);
- int value = new Random().Next(1, 4);
- switch (value)
- {
- case 1: this.Invalidate(rect1); /*refreshRect1(g);*/ toolStripStatusLabel1.Text = "Rect1"; break;
- case 2: this.Invalidate(rect2);/* refreshRect2(g);*/ toolStripStatusLabel1.Text = "Rect2"; break;
- case 3: this.Invalidate(rect3); /*refreshRect3(g);*/ toolStripStatusLabel1.Text = "Rect3"; break;
- }
- this.Update();
- }
- private void refreshRect1(Graphics g)
- {
- Color[] _colors = new Color[] { Color.Red, Color.Blue,
- Color.Yellow, Color.Tomato, Color.RosyBrown };
- Random r = new Random();
- int i= r.Next(0, 5);
- g.SetClip(rect1, System.Drawing.Drawing2D.CombineMode.Replace);
- g.FillRectangle(new SolidBrush(_colors[i]), rect1);
- }
- private void refreshRect2(Graphics g)
- {
- g.SetClip(rect2, System.Drawing.Drawing2D.CombineMode.Replace);
- g.FillRectangle(Brushes.White, rect2);
- g.DrawString(DateTime.Now.ToString("HH:mm:ss"), Font, Brushes.RosyBrown, rect2);
- }
- private void refreshRect3(Graphics g)
- {
- g.SetClip(rect3, System.Drawing.Drawing2D.CombineMode.Replace);
- g.FillRectangle(Brushes.White, rect3);
- g.TranslateTransform(25, 90);
- int i = new Random().Next(0, 360);
- g.RotateTransform(i);
- g.DrawLines(Pens.Brown, new Point[] { new Point(0, -20), new Point(-17, 10),new Point(17,0),new Point(0,-20)});
- }
- protected override void OnPaint(PaintEventArgs e)
- {
- base.OnPaint(e);
- Graphics g = e.Graphics;
- refreshRect1(g);
- refreshRect2(g);
- refreshRect3(g);
- }