2012-07-18 91 views
1

UserControl我有一個PictureBox和一些其他控件。對於包含該PictureBox的命名爲Graph我只好動用此圖片框的曲線的方法的用戶控制:在PictureBox上繪圖

//Method to draw X and Y axis on the graph 
    private bool DrawAxis(PaintEventArgs e) 
    { 
     var g = e.Graphics; 
     g.DrawLine(_penAxisMain, (float)(Graph.Bounds.Width/2), 0, (float)(Graph.Bounds.Width/2), (float)Bounds.Height); 
     g.DrawLine(_penAxisMain, 0, (float)(Graph.Bounds.Height/2), Graph.Bounds.Width, (float)(Graph.Bounds.Height/2)); 

     return true; 
    } 

    //Painting the Graph 
    private void Graph_Paint(object sender, PaintEventArgs e) 
    { 
     base.OnPaint(e); 
     DrawAxis(e); 
    } 

    //Public method to draw curve on picturebox 
    public void DrawData(PointF[] points) 
    { 
     var bmp = Graph.Image; 
     var g = Graphics.FromImage(bmp); 

     g.DrawCurve(_penAxisMain, points); 

     Graph.Image = bmp; 
     g.Dispose(); 
    } 

當應用程序啓動時,軸繪製。但是當我調用DrawData方法時,我得到的例外說bmp爲空。可能是什麼問題?

我還希望能夠多次調用DrawData以在用戶單擊某些按鈕時顯示多條曲線。達到這個目標的最好方法是什麼?

謝謝

回答

4

您從未分配過Image,對嗎?如果你想吸引你需要通過與圖片框的尺寸分配一個位圖首先創建這個圖像PictureBox「形象:

Graph.Image = new System.Drawing.Bitmap(Graph.Width, Graph.Height); 

你只需要做到這一點一次,圖像然後可以重用,如果你想重新繪製那裏的東西。

然後,您可以隨後使用此圖像進行繪製。欲瞭解更多信息,refer to the documentation

順便說一下,這完全獨立於Paint事件處理程序中的PictureBox的繪圖。後者直接使用控件,而Image作爲自動繪製在控件上的後緩衝器(但您需要調用Invalidate以在繪製後緩衝器後觸發重繪)。

此外,它使沒有意義重繪分配位圖到PictureBox.Image屬性繪製後。該操作沒有意義。

其他的東西,因爲Graphics物體是一次性的,你應該把它放在using塊中,而不是手動處理它。這確保了在例外情況下正確處理:

public void DrawData(PointF[] points) 
{ 
    var bmp = Graph.Image; 
    using(var g = Graphics.FromImage(bmp)) { 
     // Probably necessary for you: 
     g.Clear(); 
     g.DrawCurve(_penAxisMain, points); 
    } 

    Graph.Invalidate(); // Trigger redraw of the control. 
} 

您應該將此視爲固定模式。

+0

不,我沒有分配,我想在圖上調用Paint方法會使圖像。你能解釋一下,請問如何解決這個問題? – 2012-07-18 10:21:01

+0

@ Sean87查看更新。 – 2012-07-18 10:26:10

+0

@KonradRudolph非常感謝。 – 2013-10-30 08:02:33