2012-04-20 66 views
-3

我正在做一些修改我的comp103文件,我不能得到按鈕與Graphics.Clear();方法來清除圖形紙張。有人可以指出我的代碼中的錯誤,因爲我花了大約一個小時試圖在網上找到答案。Whys is Graphics.Clear();不工作在C#

對不起,要求這樣一個noob問題。

下面是代碼:

namespace Week_4_Ex1 
{ 
    public partial class Form1 : Form 
    { 
     const int height1 = 150; // A constant that stores the flags height 
     const int width1 = 100; // A constant that stores the flags width 

     public Form1() 
     { 
      InitializeComponent(); 
     } 

     /// <summary> 
     /// Button event that Draws a flag 
     /// </summary> 
     /// <param name="sender"></param> 
     /// <param name="e"></param> 
     private void btnDraw_Click(object sender, EventArgs e) 
     { 
      Graphics Paper = this.CreateGraphics(); // Creates graphics paper to draw on 
      Brush br1 = new SolidBrush(Color.Blue); // Creates a blue brush to draw with 
      Brush br2 = new SolidBrush (Color.Orange); // Creates a orange brush to draw with 
      Brush br3 = new SolidBrush (Color.Red); // Creates a red brush to draw with 

      Pen Pen1 = new Pen(Color.Blue);   // Creates a blue pen to draw with 
      Pen Pen2 = new Pen(Color.Orange);  // Creates a orange pen to draw with 
      Pen Pen3 = new Pen(Color.Red);   // Creates a red pen to draw with 

      //The following code draws a flag 
      Paper.DrawRectangle(Pen1, 10, 10, width1, height1); // Draws a blue rectangle 
      Paper.FillRectangle(br1, 10, 10, width1, height1); // Fills the rectangle with blue 
      Paper.DrawRectangle(Pen2, 110, 10, width1, height1); // Draws a blue rectangle 
      Paper.FillRectangle(br2, 110, 10, width1, height1); // Fills the rectangle with blue 
      Paper.DrawRectangle(Pen3, 210, 10, width1, height1); // Draws a blue rectangle 
      Paper.FillRectangle(br3, 210, 10, width1, height1); // Fills the rectangle with blue 

     } 
     /// <summary> 
     /// Button that closes the form 
     /// </summary> 
     /// <param name="sender"></param> 
     /// <param name="e"></param> 
     private void btnExit_Click(object sender, EventArgs e) 
     { 
      this.Close(); // Closes the form 
     } 

     /// <summary> 
     /// Clears the picturebox 
     /// </summary> 
     /// <param name="sender"></param> 
     /// <param name="e"></param> 
     private void btnErase_Click(object sender, EventArgs e) 
     { 
      Graphics.Clear(); //**THIS DOESN'T WORK** 
     } 

    } 
} 

乾杯, 拉布

+0

定義「不起作用」。 – Tudor 2012-04-20 09:37:35

+1

首先,MSDN的快速瀏覽揭示了'Clear'不是'Graphics'類型的靜態方法,並且它還需要'color'參數。 – Tudor 2012-04-20 09:39:51

+0

這是你的實際碼嗎?你的班級沒有圖形成員,並且'Graphics.Clear'方法不是靜態的... – 2012-04-20 09:41:03

回答

6

如下嘗試Graphics.Clear方法與顏色。

this.CreateGraphics().Clear(Form1.ActiveForm.BackColor); 
+0

嘿這工作,謝謝。 – Actionable 2012-04-20 09:48:09

+0

@Damith,Graphics對象是非託管對象。如果我們像這樣清除它,會導致內存泄漏嗎? – Kira 2015-09-23 09:24:52