首先參考或使用到的開源庫
https://github.com/gogopop/CameraKit-Android
https://github.com/andyb129/FlipsideCamera
使用方法:
1,首先在module級別build.gradle文件中增加依賴
compile 'com.flurgle:camerakit:0.9.17'
2,增加CameraView到布局文件中
<com.flurgle.camerakit.CameraView android:id="@+id/camera" android:layout_width="match_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" />
3,在你的activity中onResume 和 onPause 進行打開和關閉相機操作
@Override protected void onResume() { super.onResume(); cameraView.start(); } @Override protected void onPause() { cameraView.stop(); super.onPause(); }
拍攝圖片就是調用CameraView.captureImage()方法,代碼如下:
camera.setCameraListener(new CameraListener() { @Override public void onPictureTaken(byte[] picture) { super.onPictureTaken(picture); // Create a bitmap Bitmap result = BitmapFactory.decodeByteArray(picture, 0, picture.length); } }); camera.captureImage();
拍攝視頻開始是調用CameraView.startRecordingVideo()方法,結束是調用CameraView.stopRecordingVideo()方法,代碼如下:
camera.setCameraListener(new CameraListener() { @Override public void onVideoTaken(File video) { super.onVideoTaken(video); // The File parameter is an MP4 file. } }); camera.startRecordingVideo(); camera.postDelayed(new Runnable() { @Override public void run() { camera.stopRecordingVideo(); } }, 2500);
其他的一些經常使用到的屬性:
<com.flurgle.camerakit.CameraView xmlns:camerakit="http://schemas.android.com/apk/res-auto" android:id="@+id/camera" android:layout_width="match_parent" android:layout_height="wrap_content" camerakit:ckFacing="back" camerakit:ckFlash="off" camerakit:ckFocus="continuous" camerakit:ckMethod="standard" camerakit:ckZoom="pinch" camerakit:ckPermissions="strict" camerakit:ckCropOutput="true" camerakit:ckJpegQuality="100" camerakit:ckVideoQuality="480p" android:adjustViewBounds="true" />
