in a UserControl I have a PictureBox and some other controls. For the user control which contains this picturebox named as Graph I have a method to draw a curve on this picture box:
//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();
}
When application starts, the axis are drawn. but when I call the DrawData method I get the exception that says bmp is null. What can be the problem?
I also want to be able to call DrawData multiple times to show multiple curves when user clicks some buttons. What is the best way to achive this?
Thanks
You never assigned
Image, right? If you want to draw on aPictureBox’ image you need to create this image first by assigning it a bitmap with the dimensions of the PictureBox:You only need to do this once, the image can then be reused if you want to redraw whatever’s on there.
You can then subsequently use this image for drawing. For more information, refer to the documentation.
By the way, this is totally independent from drawing on the
PictureBoxin thePaintevent handler. The latter draws on the control directly, while theImageserves as a backbuffer which is painted on the control automatically (but you do need to invokeInvalidateto trigger a redraw, after drawing on the backbuffer).Furthermore, it makes no sense to re-assign the bitmap to the
PictureBox.Imageproperty after drawing. The operation is meaningless.Something else, since the
Graphicsobject is disposable, you should put it in ausingblock rather than disposing it manually. This guarantees correct disposing in the face of exceptions:You should consider this as a fixed pattern.