新建MyView类继承自SurfaceView:

public class MyView extends SurfaceView implements SurfaceHolder.Callback {

	private Paint paint;
public MyView(Context context) {
super(context);
paint=new Paint();
paint.setColor(Color.RED);
getHolder().addCallback(this);
}
public void draw(){
//绘制画布前锁定画布
Canvas canvas=getHolder().lockCanvas();
canvas.drawColor(Color.WHITE);
//从画布的50x50开始绘制,绘制到100x100,绘制面积50x50
canvas.drawRect(50, 50, 100, 100, paint);
//将第一条线顺时针旋转90度
canvas.save(); //将画布处可编辑状态
canvas.rotate(90,getWidth()/2,getHeight()/2); //按中心点进行旋转
canvas.drawLine(0, getHeight()/2, getWidth(), getHeight(), paint);
canvas.restore();// 将画布复原
canvas.drawLine(0, getHeight()/2+100, getWidth(), getHeight()+100, paint); //绘制画布结束后解锁画布
getHolder().unlockCanvasAndPost(canvas);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
} @Override
public void surfaceCreated(SurfaceHolder holder) {
draw();
} @Override
public void surfaceDestroyed(SurfaceHolder holder) {
}

MainActivity:

    @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}

效果:

Android UI SurfaceView的使用-绘制单个图型或多个图形-LMLPHP

------------

05-04 08:58