2012-07-18 93 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