爱猫的狗

拥抱变化

导航

统计

公告

Windows Forms Programming In C# 读书笔记 - 第四章 Drawing Basics

1。Drawing to the Screen

bool drawEllipse = false;

void drawEllipseButton_Click(object sender, EventArgs e) {
  drawEllipse 
= !drawEllipse;

  Graphics g 
= this.CreateGraphics();
  
try {
    
if( drawEllipse ) {
      
// Draw the ellipse
      g.FillEllipse(Brushes.DarkBlue, this.ClientRectangle);
    }

    
else {
      
// Erase the previously drawn ellipse
      g.FillEllipse(SystemBrushes.Control, this.ClientRectangle);
    }

  }

  
finally {
    g.Dispose();
  }

}

    注意:加 try-catch 块的原因是:“The Graphic class's implementation of IDisposable Dispose can release the underlying graphics object that it's maintaining.”,Graphics 对象是必须要被释放的。        此处也可以用 C# 特有的 using 块(结束后会自动调用 Dispose):
void drawEllipseButton_Click(object sender, EventArgs e) {
    
using( Graphics g = this.CreateGraphics() ) {
         
if( drawEllipse ) 
             g.FillEllipse(Brushes.DarkBlue, 
this.ClientRectangle);
         
else 
             g.FillEllipse(SystemBrushes.Control, 
this.ClientRectangle);
      }
 // g.Dispose called automatically here
}



        注意:如果想在窗口 resize 时候让椭圆自动重画。需要在 Form 类的constructor中加入 this.SetStyle(ControlStyles.ResizeRedraw, true) ;    同时在 button click事件中加入 this.Refresh();(相当于 this.Invalidate(true) 加上 this.Update();但是 resize 时候自动重画全部窗口的效率不高,比较费时。

2。Saving and Restoring Graphics Settings

 使用 System.Drawing. Drawing2D namespace 中的 GraphicsState 对象,再加上 Graphics 类的 Save() 和 Restore() 方法
void DrawSomething(Graphics g) {
  
// 保存旧的
  GraphicsState oldState = g.Save();

  
// 改变一下平滑模式
  g.SmoothingMode = SmoothingMode.AntiAlias;

  
// 开始画

  
// 恢复旧的
  g.Restore(oldState);
}


posted on 2005-03-03 12:55 anf 阅读(313) 评论(0) 编辑 收藏