surfaceview组件的初始化

时间:2021-03-23 19:37:25

在activity中onCreate里,直接操作surfaceview,是无法成功的。

像以下代码:

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.trace);

    TraceView=(SurfaceView) findViewById(R.id.TraceView);

  TraceViewHolder=TraceView.getHolder();  

   Canvas canvas = TraceViewHolder.lockCanvas(); 

canvas.drawColor(Color.WHITE);                  //设置背景颜色  
Paint p = new Paint();
 p.setStyle(Style.STROKE);
 p.setStrokeWidth(2);
 p.setColor(Color.BLUE); 
 canvas.drawLine(10, 0,10, 400, p);
if (canvas!=null)  TraceViewHolder.unlockCanvasAndPost(canvas);


}

运行完后,surfaceview里黑乎乎一片,没有想要的线条。


要添加 surfaceviewHolder的Callback函数,才能实现。代码如下:

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.trace);

    TraceView=(SurfaceView) findViewById(R.id.TraceView);

///////////////三个函数缺一不可。surfaceCreated, surfaceChanged,surfaceDestroyed /////

TraceView.getHolder().addCallback(new Callback() { 

public void surfaceCreated(SurfaceHolder holder) { 

  Canvas canvas = holder.lockCanvas();  
canvas.drawColor(Color.WHITE);                  //设置背景颜色  
Log.i("TraceView Callback","OK");
Paint p = new Paint();
 p.setStyle(Style.STROKE);
 p.setStrokeWidth(1);
 p.setColor(Color.BLUE); 
//  canvas.drawLine(20, 0,20, 400, p);
 DrawGrid(canvas,p,10);  
if (canvas!=null)  holder.unlockCanvasAndPost(canvas);
}

public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
// Log.i("TraceView Changed Callback","OK");
}

public void surfaceDestroyed(SurfaceHolder holder){

}



}); 


/////////////////////////



}