参考资料: Android游戏编程之从零开始
涉及的相关知识点: 1、Callback 一个SurfaceView一定要实现一个SurfaceHolder.Callback接口。以便在底层的Surface状态发生变化的时候通知View,该接口需要实现以下3个方法: public void surfaceCreated(SurfaceHolder holder) {} public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){} public void surfaceDestroyed(SurfaceHolder holder) {} 2、SurfaceHolder 这是一个用于控制surface的接口,它提供了控制surface 的大小,格式等 SurfaceView的getHolder()函数可以获取SurfaceHolder对象,Surface 就在SurfaceHolder对象内。 3、具体代码 MySurfaceView.java package cn.llbb.testsurfaceviewdemo; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.view.SurfaceHolder; import android.view.SurfaceHolder.Callback; import android.view.SurfaceView; public class MySurfaceView extends SurfaceView implements Callback { private SurfaceHolder sfh; private Canvas canvas; private Paint paint; public MySurfaceView(Context context) { super(context); sfh = getHolder(); sfh.addCallback(this); paint = new Paint(); paint.setColor(Color.RED); setFocusable(true); } public void surfaceCreated(SurfaceHolder holder) { MyDraw(); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } public void surfaceDestroyed(SurfaceHolder holder) { } private void MyDraw(){ try{ canvas = sfh.lockCanvas(); if(canvas != null){ canvas.drawColor(Color.WHITE); canvas.drawText("drawtext", 10, 10, paint); canvas.drawPoint(10, 20, paint); canvas.drawPoints(new float[]{10,30,30,30}, paint); canvas.drawLine(10,40,50,40, paint); canvas.drawLines(new float[]{10,50,50,50,70,50,110,50}, paint); canvas.drawRect(10,60,40,100, paint); Rect rect = new Rect(10,110,60,130); canvas.drawRect(rect, paint); RectF rectf = new RectF(10,140,60,170); canvas.drawRoundRect(rectf, 20, 20, paint); canvas.drawCircle(20, 200, 20, paint); canvas.drawArc(new RectF(150,20,200,70), 0, 230, true, paint); canvas.drawOval(new RectF(150,80,180,100), paint); Path path = new Path(); path.moveTo(160,150); path.lineTo(200,150); path.lineTo(180,200); path.close(); canvas.drawPath(path, paint); Path pathcircle = new Path(); pathcircle.addCircle(130, 260, 20, Path.Direction.CCW); canvas.drawTextOnPath("pathtext", pathcircle, 10, 20, paint); } }catch(Exception e){ }finally{ sfh.unlockCanvasAndPost(canvas); } } } MainActivity.java package cn.llbb.testcanvasdemo; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.view.WindowManager; public class MainActivity extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); //getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(new MySurfaceView(this)); } } 效果图: