让自己开发的照相软件也可以自动对焦

  • Post author:
  • Post category:其他


拍照button按下时

mCamera.autoFocus(mAutoFocusCallBack);

自动对焦回调函数mAutoFocusCallBack


private AutoFocusCallback mAutoFocusCallBack = new AutoFocusCallback() {

@Override
public void onAutoFocus(boolean success, Camera camera) {

if (success) {

mInProgress = true;

// set parameters of camera
Camera.Parameters Parameters = mCamera.getParameters();
Parameters.setPreviewSize(IMG_PREVIEW_WIDTH, IMG_PREVIEW_HEIGHT);
Parameters.setPictureSize(IMG_WIDTH, IMG_HEIGHT);
mCamera.setParameters(Parameters);

mCamera.takePicture(mShutterListener, null, mImageCaptureCallback);
}
}
};

设置Camera.Parameters好像有些问题,如果设置了相机(或者是SDK)不支持的分辨率就会报错,估计要添加判断。

目前的设置为


private static int IMG_PREVIEW_WIDTH = 480;
private static int IMG_PREVIEW_HEIGHT = 320;
private static int IMG_WIDTH = 1280;
private static int IMG_HEIGHT = 960;

监听事件mShutterListener


private Camera.ShutterCallback mShutterListener = new Camera.ShutterCallback() {
public void onShutter() {
}
};

拍照回调函数mImageCaptureCallback

这里使用了线程,因为考虑到保存图片时一般都会显示一个progress dialog,如果不用线程的话,dialog画面会定在那里,无法起到预期的效果。

当然不用线程也不会有错,适当修改一下就可以了。


private PictureCallback mImageCaptureCallback = new PictureCallback() {

@Override
public void onPictureTaken(final byte[] data, Camera camera) {

new Thread(new Runnable() {

@Override
public void run() {

// get path to save image file
String filePath = "/sdcard/DCIM/Camera";

// generate file name
String name = "mytest.jpg";
String fileName = filePath + name;

FileOutputStream fos = null;
try {
// saving file
fos = new FileOutputStream(fileName);
fos.write(data);
fos.close();

} catch (Exception e) {

// close file if error
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
throw e;
} catch (Exception e1) {
e1.printStackTrace();
}
}
// close scene
finish();
}
}
}).start();
}
};

最后提醒一下,别忘记在AndroidManifest.xml里增加


<uses-permission android:name="android.permission.CAMERA" />

好了,就写那么多吧,希望对大家有用。



版权声明:本文为DaiLM原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。