Camera的使用。横竖屏,画面不变形
jiep.png 0005.png一、调用系统提供的拍照
private void takePic() {
String imgPath = "/sdcard/test/img.jpg";
File file = new File(imgPath);
if(!file.exists()){
File parentFile = file.getParentFile();
parentFile.mkdirs();
}
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent,100);
}
二、自定义Camera
调用系统的Camera 实现拍照,UI界面是系统提供的,定制性降低了 。
创建类继承与SurfaceView,并addCallback(this),在回调初始化预览
@Override
public void surfaceCreated(SurfaceHolder holder) {
setStartPreview(mCamera, holder);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.e("surfaceChanged", " ---- width = " + width + " height = " + height);
Log.e("surfaceChanged", "-----> getDeviceHeight = " + getDeviceHeight());
mSurfaceWidth = width;
mSurfaceHeight = height;
if (mSurfaceHolder.getSurface() == null || mCamera == null) {
return;
}
try {
mCamera.stopPreview();
}catch (Exception e){
e.printStackTrace();
}
setStartPreview(mCamera,mSurfaceHolder);
setCameraParams(width, height);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
releaseCamera();
}
- surfaceChanged:拍照状态改变时调用。当我们切换横竖屏会调用该方法,需要对预览界面大previewsize进行处理不然画面会拉伸的很厉害。在
setCameraParams(width, height);
设置camera预览参数
public void setCameraParams(int width, int height){
Camera.Parameters parameters = mCamera.getParameters();
List<Camera.Size> supportedPictureSizes = parameters.getSupportedPictureSizes();
List<Camera.Size> videoSizes = parameters.getSupportedVideoSizes();
Camera.Size optimalVideoSize = CameraHelper.getOptimalVideoSize(videoSizes, supportedPictureSizes, width, height);
parameters.setPictureFormat(ImageFormat.JPEG);
Log.e("setCameraParams","----- width = " +optimalVideoSize.width +" height = " + optimalVideoSize.height);
parameters.setPreviewSize(optimalVideoSize.width, optimalVideoSize.height);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
mCamera.setParameters(parameters);
}
主要使用了CameraHelper,在 Android 中录制视频时显示的 Size 和实际拍照的 Size 是由 Camera 所决定的,最好的方法是计算出可支持的 PreviewSize 和 VideoSize 计算出一个合适的size,同时根据自己视频的用途,选择合理的 Size
CameraHelper 参考自 GoogleCameraSample 帮助你计算出合适的 Size
- surfaceCreated:当surface被创建的时候调用。在
setStartPreview
方法初始化预览
public void setStartPreview(Camera camera, SurfaceHolder surfaceHolder) {
try {
Log.e("setStartPreview", "---- mIsPortrait = " + mIsPortrait);
camera.setPreviewDisplay(surfaceHolder);
if(mIsPortrait){
camera.setDisplayOrientation(90);
}else{
camera.setDisplayOrientation(0);
}
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
- surfaceDestroyed:主要是在surface被销毁的时候做一些回收的工作。
拍照
public void capture(View view) {
//自动对焦
mCamera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
Log.e("autoFocus", "----- success = " + success);
if (success) {
mCamera.takePicture(null,null,null,mPictureCallback);
}
}
});
}
在mPictureCallback回调获取拍照返回。
END
网友评论