Graphics.FromImage(bitmap)的问题,为什么每次都要重新new bitmap
使用Bitmap对控件进行绘图,并且令控件的Background为Bitmap,代码如下
Bitmap bitmap;//申明为类成员
Graphics graph;
private void createImage()
{//调用的时候先调用createImage方法
bitmap=new Bitmap(this.Width,this.Height);
graph=new Graphics.FromImage(bitmap);
}
private void updateImage()
{
bitmap=new Bitmap(this.Width,this.Height);//问题在于为什么一定要在此处对bitmap重新new,
//如果不重新new就显示不出线条
graph=new Graphics.FromImage(bitmap);
graph.DrawLine(pen,0,2,20,50);
this.BackgroundImage=bitmap;
}
//如果这样写就不会有图形
private void updateImage()
{
graph.DrawLine(pen,0,2,20,50);
this.BackgroundImage=bitmap;
}
private Bitmap bitmap;
private Graphics graph;
private Pen penWave = new Pen(Color.Lime);
private Pen penGrid = new Pen(Color.Gray);
protected override void OnLoad(EventArgs e)
{
//打开双缓冲,防止闪烁
DoubleBuffered = true;
canvas_height = base.ClientSize.Height;
canvas_width = base.ClientSize.Width;
CreateImage();
DrawGrids(ref graph);
this.BackgroundImage = bitmap;
}
protected override void OnResize(EventArgs e)
{
canvas_height = base.ClientSize.Height;
canvas_width = base.ClientSize.Width;
this.Refresh();
}
private void DrawGrids()
{//画网格
//pos,canvas_height都是变量,不重复贴了,不影响整体
graph.DrawLine(penGrid, pos, 0, pos, canvas_height);//基本上都是这种代码,不重复贴,没做别的处理
}
private void DrawWave()
{
graph.DrawLine(penWave,0,2,20,50);//基本上都是这种,两点之间连线的,不重复贴代码了
}
//调用的时候,会先调用这个CreateImage()方法,再调用UpdateImage
//CreateImage只调用一次,UpdateImage会调用多次
public void CreateImage()
{
bitmap=new Bitmap(this.Width,this.Height);
graph=new Graphics.FromImage(bitmap);
}
public void UpdateImage()
{//经过反复试验,在这个方法里必须要对bitmap重新new,否则看不到两点间的连线
DrawDot();
this.Refresh();
}
this.BackgroundImage = bitmap;
bitmap是一个引用类型。当你再次设置 this.BackgroundImage = bitmap;的时候,其实什么都没做,因为 this.BackgroundImage所指向的内存地址已经是bitmap了。这个时候不会自动触发窗体print事件。当你在
this.BackgroundImage = bitmap;之前加了bitmap=new Bitmap()之后,bitmap的内存地址发生了重新分配,这样
BackgroundImage发现接收的内存地址发生了变化,于是触发了窗体print事件。
最终的原因还是因为:你没有找着对象。
[解决办法]
private void updateImage()
{
graph.DrawLine(pen,0,2,20,50);
this.BackgroundImage=bitmap;
}
private void updateImage()
{
graph.DrawLine(pen,0,2,20,50);
this.BackgroundImage=bitmap;
OnBackgroundImageChanged(new EventArgs());
}