Android 使Camera预览清晰,循环自动对焦处理

潘嘉佑
2023-12-01
我们经常使用SurfaceView显示Camera预览画面,但画面基本都不清晰。主要是因为没有自动对焦,而自动对焦触发是通过mCamera.autoFocus(autoFocusCallback);这个函数,但是只会起一次作用,后面画面清晰度有一直这样,但是随着拍摄目标的距离变化,这个画面不在清晰,需要再次对焦。所以我这里主要通过循环自动对焦来完成。

SurfaceView如何显示Camera预览画面,这个我不多说

创建一个Handler用来触发自动对焦

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                Log.v("zzw",""+msg.what);
                switch (msg.what){
                    case MSG_AUTOFUCS:
                        mCamera.autoFocus(autoFocusCallback);
                        break;
                }
            }
        };
然后我们如果要调用autoFocus函数,就需要实例化AutoFocusCallback,然后我们在他自动对焦返回结果的函数里,添加调用handler延迟1.3秒来触发自动对焦


final class AutoFocusCallback implements Camera.AutoFocusCallback {
    private static final String TAG = AutoFocusCallback.class.getName();
    private static final long AUTO_FOCUS_INTERVAL_MS = 1300L; //自动对焦时间

    private Handler mAutoFocusHandler;
    private int mAutoFocusMessage;

    void setHandler(Handler autoFocusHandler, int autoFocusMessage) {
        this.mAutoFocusHandler = autoFocusHandler;
        this.mAutoFocusMessage = autoFocusMessage;
    }

    @Override
    public void onAutoFocus(boolean success, Camera camera) {
        Log.v("zzw", "autof focus "+success);
        if (mAutoFocusHandler != null) {
            mAutoFocusHandler.sendEmptyMessageDelayed(mAutoFocusMessage,AUTO_FOCUS_INTERVAL_MS);
//            mAutoFocusHandler = null;
        } else {
            Log.v(TAG, "Got auto-focus callback, but no handler for it");
        }
    }
}

所以我们在Activity的onCreate里还需要将handler和msg.what编号给AutoFocusCallback

        autoFocusCallback = new AutoFocusCallback();
        autoFocusCallback.setHandler(handler,MSG_AUTOFUCS);

以下是Activity的完整代码

public class TwoActivity extends Activity implements SurfaceHolder.Callback{
    private static final String TAG = "ChrisAcvitity";
    private Camera mCamera;
    private SurfaceHolder mHolder;
    private SurfaceView mView;
    private static final int MSG_AUTOFUCS = 1001;

    private Handler handler;
    AutoFocusCallback autoFocusCallback;
    @Override
    // 创建Activity时执行的动作
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);

        mView = (SurfaceView) findViewById(R.id.sv);
        mHolder = mView.getHolder();
        mHolder.addCallback(this);


        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                Log.v("zzw",""+msg.what);
                switch (msg.what){
                    case MSG_AUTOFUCS:
                        mCamera.autoFocus(autoFocusCallback);
                        break;
                }
            }
        };
        autoFocusCallback = new AutoFocusCallback();
        autoFocusCallback.setHandler(handler,MSG_AUTOFUCS);
    }

    @Override
    // apk暂停时执行的动作:把相机关闭,避免占用导致其他应用无法使用相机
    protected void onPause() {
        super.onPause();
        handler.removeCallbacksAndMessages(null);
        mCamera.setPreviewCallback(null);
        mCamera.stopPreview();
        mCamera.release();
        mCamera = null;
    }

    @Override
    // 恢复apk时执行的动作
    protected void onResume() {
        super.onResume();
        if (null!=mCamera){
            mCamera = getCameraInstance();
            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();
            } catch(IOException e) {
                Log.d(TAG, "Error setting camera preview: " + e.getMessage());
            }
        }
    }


    // SurfaceHolder.Callback必须实现的方法
    public void surfaceCreated(SurfaceHolder holder){
        mCamera = getCameraInstance();
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch(IOException e) {
            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

    // SurfaceHolder.Callback必须实现的方法
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
        refreshCamera(); // 这一步是否多余?在以后复杂的使用场景下,此步骤是必须的。
        int rotation = getDisplayOrientation(); //获取当前窗口方向
        mCamera.setDisplayOrientation(rotation); //设定相机显示方向
    }

    // SurfaceHolder.Callback必须实现的方法
    public void surfaceDestroyed(SurfaceHolder holder){
        mHolder.removeCallback(this);
        if(mCamera != null){
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }

    }

    // === 以下是各种辅助函数 ===

    // 获取camera实例
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open();
        } catch(Exception e){
            Log.d("TAG", "camera is not available");
        }
        return c;
    }

    // 获取当前窗口管理器显示方向
    private int getDisplayOrientation(){
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        int rotation = display.getRotation();
        int degrees = 0;
        switch (rotation){
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        android.hardware.Camera.CameraInfo camInfo =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(Camera.CameraInfo.CAMERA_FACING_BACK, camInfo);

        // 这里其实还是不太懂:为什么要获取camInfo的方向呢?相当于相机标定??
        int result = (camInfo.orientation - degrees + 360) % 360;

        return result;
    }

    // 刷新相机
    private void refreshCamera(){
        if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch(Exception e){
            // ignore: tried to stop a non-existent preview
        }

        // set preview size and make any resize, rotate or
        // reformatting changes here
        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();
            mCamera.autoFocus(autoFocusCallback);
        } catch (Exception e) {

        }
    }

}

还有权限

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

 类似资料: