2011-04-27 86 views
0

我在C#中創建了一個小應用程序,在該應用程序中,當鼠標移動時繪製一個矩形。On Image Drawing保存

但是,當表格被最小化或最大化時,繪圖被擦除。另外,當我再次繪製時,第一個矩形的繪製將被刪除。

我該如何解決這個問題?這裏是我目前擁有的代碼:

int X, Y; 
    Graphics G; 
    Rectangle Rec; 
    int UpX, UpY, DwX, DwY; 


    public Form1() 
    { 
     InitializeComponent(); 
     //G = panel1.CreateGraphics(); 
     //Rec = new Rectangle(X, Y, panel1.Width, panel1.Height); 
    } 


    private void pictureBox1_MouseDown(object sender, MouseEventArgs e) 
    { 
     UpX = e.X; 
     UpY = e.Y; 
     //Rec = new Rectangle(e.X, e.Y, 0, 0); 
     //this.Invalidate(); 
    } 

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e) 
    { 
     DwX = e.X; 
     DwY = e.Y; 

     Rec = new Rectangle(UpX, UpY, DwX - UpX, DwY - UpY); 
     Graphics G = pictureBox1.CreateGraphics(); 
     using (Pen pen = new Pen(Color.Red, 2)) 
     { 
      G.DrawRectangle(pen, Rec); 
     } 
    } 

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e) 
    {    
     if (e.Button == MouseButtons.Left) 
     { 
      // Draws the rectangle as the mouse moves 
      Rec = new Rectangle(UpX, UpY, e.X - UpX, e.Y - UpY); 
      Graphics G = pictureBox1.CreateGraphics(); 

      using (Pen pen = new Pen(Color.Red, 2)) 
      { 
       G.DrawRectangle(pen, Rec); 
      } 
      G.Save(); 
      pictureBox1.SuspendLayout(); 
      pictureBox1.Invalidate(); 

     } 

    } 

    private void pictureBox1_Paint(object sender, PaintEventArgs e) 
    { 
     pictureBox1.Update();    
    } 
+2

你不需要大寫每一個單詞。 – alex 2011-04-27 11:31:36

回答

2

爲什麼你的圖紙越來越刪除的原因是因爲你拉進你通過調用CreateGraphics方法獲得的Graphics對象。特別是,該行代碼的不正確:

Graphics G = pictureBox1.CreateGraphics(); 

正如你已經發現,每當形式是重新粉刷(當它被最大化,最小化其發生,覆蓋另一個物體在屏幕上,或在許多其他可能的情況下),您已經吸引到該臨時對象中的所有內容都將丟失。表單完全用其內部繪畫邏輯重新繪製自己;它完全被遺忘了你暫時在它上面畫的東西。

中的WinForms繪製殘影的正確方法是重寫要畫到控制OnPaint method(或者,你也可以處理Paint event)。所以,如果你想畫到您的表單,你把你的繪製代碼到下面的方法:

protected override void OnPaint(PaintEventArgs e) 
{ 
    // Call the base class first 
    base.OnPaint(e); 

    // Then insert your custom drawing code 
    Rec = new Rectangle(UpX, UpY, DwX - UpX, DwY - UpY); 
    using (Pen pen = new Pen(Color.Red, 2)) 
    { 
     e.Graphics.DrawRectangle(pen, Rec); 
    } 
} 

,並觸發重新油漆,你只需要調用任意鼠標事件的Invalidate methodMouseDownMouseMoveMouseUp):但是

this.Invalidate(); 

注意的是,絕對沒有理由叫Update methodPaint事件處理程序。所有調用Update方法的做法是強制控件重新繪製自己。但是,Paint事件發生時已經發生了!