用处就是绘画
1、在布局文件中定义一个SurfaceView。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开始绘画"
android:id="@+id/btn_paint"/>
</LinearLayout>
<SurfaceView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/sf_view"
android:layout_gravity="center"/>
</LinearLayout>
2、获取SerfaceView对象,然后通过getHolder,就获取了操作对象。
private void initView(){
btn_paint = (Button)this.findViewById(R.id.btn_paint);
surface = (SurfaceView) this.findViewById(R.id.sf_view);
holder = surface.getHolder();
}
3、给surfaceHolder添加监听事件。
holder.addCallback(this);
4、重写Callback接口中的方法
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
new Thread(new PaintLine()).start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
class PaintLine implements Runnable{
@Override
public void run() {
Canvas canvas = holder.lockCanvas(null);
Paint paint = new Paint();
paint.setColor(Color.BLUE);
//for(int x= width / 2;x< width;x++)
//canvas.drawPoint(x, x*x, paint);
canvas.drawRect(new Rect(0,0,80,80), paint);
holder.unlockCanvasAndPost(canvas);
}
}