2011-04-27 80 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事件发生时已经发生了!