android高级技术之相机的前后摄像头切换

android高级技术之相机(一):http://blog.csdn.net/program008/article/details/50557296

前面的分享中我们学习了相机的基本属性,包括相机的预览属性,拍照,保存相片,旋转相片等,今天我们来看下关于相机的前后摄像头的切换:

在之前的代码中做稍微的更改即可实现摄像头的切换:

一、获取相机信息,得到前置摄像头和后置摄像头的编号: 

protected void getCameraInfo(){
    Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
    iCameraCnt = Camera.getNumberOfCameras();

    for (int i = 0; i < iCameraCnt; i++) {
        Camera.getCameraInfo(i,cameraInfo);
        if(cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT){
               iFontCameraIndex = i;
         }
        else if(cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK){
                iBackCameraIndex = i;

         }

    }

}

二、surfaceCreated回调时,开始打开后面的摄像头,并标示好

@Override
public void surfaceCreated(SurfaceHolder holder) {
    getCameraInfo();
    mCamera = Camera.open(iBackCameraIndex);
    bBack = true;
    try {
        setCamera();
        mCamera.setPreviewDisplay(holder);
        mCamera.startPreview();

      } catch (IOException e) {
        e.printStackTrace();
      }

}

三、点击切换摄像头时:

public void onChange(View view) {
      if (mCamera != null) {
           mCamera.release();
           mCamera = null;
       }
     if (bBack){
         mCamera = Camera.open(iFontCameraIndex);
         setCamera();
        try {
             mCamera.setPreviewDisplay(mSfPreview.getHolder());
         } catch (IOException e) {
              e.printStackTrace();
       }
       mCamera.startPreview();
       bBack = false;
     }
     else{
         mCamera = Camera.open(iBackCameraIndex);
         setCamera();
         try {
             mCamera.setPreviewDisplay(mSfPreview.getHolder());
          } catch (IOException e) {
              e.printStackTrace();
          }
         mCamera.startPreview();
         bBack = true;
    }

}
学习上面的代码需要结合上期的相机的开发步骤一起学习,地址链接: http://blog.csdn.net/program008/article/details/50557296


你可能感兴趣的:(android高级技术之相机的前后摄像头切换)