2016-10-25 48 views
-1

我已經創建繪圖程序。它使用System.graphics在窗體上的panel1上繪製矩形等。 Graphics 鼠標繪製事件: Draw 我想從PANEL1作爲位圖獲得藝術,嘗試這種代碼:保存System.Graphics位圖不起作用

using (var bmp = new Bitmap(panel1.Width, panel1.Height)) 
{ 
    panel1.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height)); 
    bmp.Save("output.png", System.Drawing.Imaging.ImageFormat.Jpeg); 
} 

,但它產生PANEL1的背景顏色圖像

+1

不要創建任意功能'Graphics'對象。使用在「Paint」事件中傳遞的對象並僅在此事件的事件處理程序中繪製。這也將解決save-to-file問題。並且請將代碼作爲文字加入,而不是圖像。 –

回答

1

一個處理程序添加到面板的Paint事件某處(例如形式構造函數):

panel1.Paint += panel1_Paint; 

[重新]事件繪製任何圖形:

void panel1_Paint(object sender, PaintEventArgs e) 
{    
    DrawLine(e.Graphics); 
} 

保存時,你的代碼應該只是罰款:

private void button1_Click(object sender, EventArgs e) 
{ 
    using (var bmp = new Bitmap(panel1.Width, panel1.Height)) 
    { 
     panel1.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height)); 
     bmp.Save("c:\\temp\\output.png", System.Drawing.Imaging.ImageFormat.Jpeg); 
    } 
}