2013-02-03 129 views
0

我試圖將面板上的圖像保存到BMP,並且只要保存,就只有一張空白圖像。如何將面板保存爲BMP

繪圖代碼

private void DrawingPanel_MouseMove(object sender, MouseEventArgs e) 
    { 
     OldPoint = NewPoint; 
     NewPoint = new Point(e.X, e.Y); 

     if (e.Button == MouseButtons.Left) 
     { 
      Brush brush = new SolidBrush(Color.Red); 
      Pen pen = new Pen(brush, 1); 

      DrawingPanel.CreateGraphics().DrawLine(pen, OldPoint, NewPoint); 
     } 
    } 

可以節省代碼

void SaveBMP(string location) 
    { 
     Bitmap bmp = new Bitmap((int)DrawingPanel.Width, (int)DrawingPanel.Height); 
     DrawingPanel.DrawToBitmap(bmp, new Rectangle(0, 0, DrawingPanel.Width, DrawingPanel.Height)); 

     FileStream saveStream = new FileStream(location + ".bmp", FileMode.OpenOrCreate); 
     bmp.Save(saveStream, ImageFormat.Bmp); 

     saveStream.Flush(); 
     saveStream.Close(); 
    } 

最終結果

這是我畫

What I drew

這是節省

What is saved

+0

那麼,你必須把畫中的面板漆事件,由於面板將無法保存的DrawLine,你只需添加「動態」。 – Patrick

+0

您是否嘗試覆蓋面板並在重寫OnPaint方法中對其進行繪製?這就是像這樣的自定義控制繪圖遵循的一般模式。 由於DrawBitmap方法可能再次繪製整個控件而不是繪製您當前在屏幕上看到的任何內容,因此您對當前代碼無效,這對我來說很有意義。 – steinar

+0

@steinar我該如何做到這一點?你能舉一個例子答覆,謝謝。 – ixenocider

回答

2

你必須改變你的代碼,以便它覆蓋OnPaint方法。這是定製控件外觀時遵循的默認模式。

爲什麼你的特定代碼不起作用的原因是DrawToBitmap在調用時肯定會重繪整個控件。在這種情況下,該方法不知道您的自定義圖紙到控件。

這裏是一個工作示例:

public partial class DrawingPanel : Panel 
{ 
    private List<Point> drawnPoints; 

    public DrawingPanel() 
    { 
     InitializeComponent(); 
     drawnPoints = new List<Point>(); 

     // Double buffering is needed for drawing this smoothly, 
     // else we'll experience flickering 
     // since we call invalidate for the whole control. 
     this.DoubleBuffered = true; 
    } 

    protected override void OnPaint(PaintEventArgs e) 
    { 
     base.OnPaint(e); 

     // NOTE: You would want to optimize the object allocations, 
     // e.g. creating the brush and pen in the constructor 
     using (Brush brush = new SolidBrush(Color.Red)) 
     { 
      using (Pen pen = new Pen(brush, 1)) 
      { 
       // Redraw the stuff: 
       for (int i = 1; i < drawnPoints.Count; i++) 
       { 
        e.Graphics.DrawLine(pen, drawnPoints[i - 1], drawnPoints[i]); 
       } 
      } 
     } 
    } 

    protected override void OnMouseMove(MouseEventArgs e) 
    { 
     base.OnMouseMove(e); 

     // Just saving the painted data here: 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 
      drawnPoints.Add(e.Location); 
      this.Invalidate(); 
     } 
    } 

    public void SaveBitmap(string location) 
    { 
     Bitmap bmp = new Bitmap((int)Width, (int)Height); 
     DrawToBitmap(bmp, new Rectangle(0, 0, Width, Height)); 

     using (FileStream saveStream = new FileStream(location + ".bmp", FileMode.OpenOrCreate)) 
     { 
      bmp.Save(saveStream, ImageFormat.Bmp); 
     }      
    } 
} 
+0

謝謝,這工作! – ixenocider