日期:2014-05-17  浏览次数:20858 次

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;
}


调用的时候是先调用的createImage(),先创建了bitmap和graph,然后再调用updateImage()方法,但是在updateImage里一定要对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();
     &nb