自定義SurfaceView 主要步驟: 實現SurfaceHolder.Callback介面,創建SurfaceView的生命周期 實現Camera.PreviewCallback介面,創建預覽回調介面 創建Camera打開相機 實例: FrameCallback回調介面 MainActivity ...
自定義SurfaceView
主要步驟:
實現SurfaceHolder.Callback介面,創建SurfaceView的生命周期
實現Camera.PreviewCallback介面,創建預覽回調介面
創建Camera打開相機
實例:
public class CameraSurfaceViews extends SurfaceView implements SurfaceHolder.Callback, Camera.PreviewCallback{ Context mContext; SurfaceHolder mSurfaceHolder;//surface的控制器 Camera mCamera;//相機類 FrameCallback mCb;//數據回調介面 public void setmCb(FrameCallback mCb) { this.mCb = mCb; }
//獲取surfaceView的SurfaceHolder對象和介面 public CameraSurfaceViews(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; mSurfaceHolder = getHolder(); mSurfaceHolder.addCallback(this); }
//尋找相機 private int findCamera(boolean isfront) { int cameraCount = 0; Camera.CameraInfo cameraInfo = new Camera.CameraInfo(); cameraCount = Camera.getNumberOfCameras(); for (int camIdx = 0; camIdx < cameraCount; camIdx++) { Camera.getCameraInfo(camIdx, cameraInfo); if (isfront) { // CAMERA_FACING_FRONT前置 if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { return camIdx; } } else { // CAMERA_FACING_BACK後置 if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) { return camIdx; } } } return -1; } //打開相機 private Camera getCamera() { Camera camera = null; int cameraId = findCamera(false); try { if(cameraId==1){ camera = Camera.open(cameraId ); }else if(cameraId==0)( camera = Camera.open(0); }
} catch (Exception e) { camera = null; } return camera; } //surface被創建時調用 @Override public void surfaceCreated(SurfaceHolder holder) { mCamera = getCamera();
}
//surface大小被改變時調用 @Override public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) { setStartPreview(mCamera,mSurfaceHolder);
}
//surface被銷毀時調用 @Override public void surfaceDestroyed(SurfaceHolder holder) { releaseCamera(); } //開啟相機預覽 private void setStartPreview(Camera camera, SurfaceHolder holder) { try { mCamera.setPreviewDisplay(holder); mCamera.setPreviewCallback(this); camera.startPreview(); } catch (IOException e) { } }
//釋放Camera public void releaseCamera() { if (mCamera != null) { mCamera.setPreviewCallback(null); mCamera.stopPreview();// 停掉攝像頭的預覽 mCamera.release(); mCamera = null; } }
//預覽回調,傳遞yuv視頻流數據 @Override public void onPreviewFrame(byte[] bytes, Camera camera) { // Log.i("onPreviewFrame",""+ bytes); if(mCb!= null){ mCb.onDecodeFrame(bytes); } } }
FrameCallback回調介面
public interface FrameCallback { void onDecodeFrame(byte[] data) ; }
MainActivity
public class MainActivity extends AppCompatActivity implements FrameCallback{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public void onDecodeFrame(byte[] data) { //實時處理yuv視頻流數據 } }