Android音频开发之SurfaceView的使用详解

  public class SurfaceViewTest extends SurfaceView implements SurfaceHolder.Callback{

  private SurfaceHolder mSurfaceHolder;

  private Canvas mCanvas;

  private Paint paint;

  public SurfaceViewTest(Context context) {

  this(context,null,0);

  }

  public SurfaceViewTest(Context context, AttributeSet attrs) {

  this(context, attrs,0);

  }

  public SurfaceViewTest(Context context, AttributeSet attrs, int defStyleAttr) {

  super(context, attrs, defStyleAttr);

  init();

  }

  private void init() {

  mSurfaceHolder = getHolder(); // 初始化

  mSurfaceHolder.addCallback(this);

  setFocusable(true);

  setFocusableInTouchMode(true);

  this.setKeepScreenOn(true);

  paint = new Paint(Paint.ANTI_ALIAS_FLAG);

  paint.setColor(Color.RED);

  paint.setStrokeWidth(5);

  paint.setStyle(Paint.Style.STROKE);

  }

  @Override

  public void surfaceCreated(SurfaceHolder holder) {

  // 创建成功后就能通过线程绘制自定义内容

  new Thread(new Runnable() {

  @Override

  public void run() {

  draw();

  }

  }).start();

  }

  private void draw() {

  try {

  mCanvas = mSurfaceHolder.lockCanvas();

  mCanvas.drawCircle(500,500,300,paint);

  mCanvas.drawCircle(100,100,20,paint);

  } catch (Exception e) {

  e.printStackTrace();

  } finally {

  if (mCanvas != null)

  mSurfaceHolder.unlockCanvasAndPost(mCanvas);

  }

  }

  @Override

  public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}

  @Override

  public void surfaceDestroyed(SurfaceHolder holder) {}

  }