Android Camera2 API - 检测何时有焦点

Android Camera2 API - Detect when we have focus

所以,我设法用我想要的方式用旧相机创建了我想要的功能。

与mCamera.autoFocus(autoFocusCallback);我在预览模式下检测到我何时获得焦点和 运行 所需的代码。

现在我很难掌握如何在 camera2 中做同样的事情 API。 我的第一个想法是我会使用

        private void process(CaptureResult result) {
        switch (mState) {
            case STATE_PREVIEW: {
                // We have nothing to do when the camera preview is working normally.
                int afState = result.get(CaptureResult.CONTROL_AF_STATE);
                //if (CaptureResult.CONTROL_AF_STATE == afState) {
                    Log.d("SOME KIND OF FOCUS", "WE HAVE");
                //}

                break;
            }
}

但我找不到某种状态告诉我我们已经获得焦点。有人知道如何使用 Camera2 API 完成此操作吗?

你基本上明白了。您可以检查的状态列表及其转换可以在 here.

中找到

这取决于您使用的 CONTROL_AF_MODE,但通常您会检查 FOCUSED_LOCKEDPASSIVE_FOCUSED,尽管您可能想要 NOT_FOCUSED_LOCKEDPASSIVE_UNFOCUSED 以防相机 无法 聚焦场景。

对于那些感兴趣的人,我最终得到了这样的混合:

private CameraCaptureSession.CaptureCallback mCaptureCallback
        = new CameraCaptureSession.CaptureCallback() {

    private void process(CaptureResult result) {
        switch (mState) {
            case STATE_PREVIEW: {

                int afState = result.get(CaptureResult.CONTROL_AF_STATE);
                if (CaptureResult.CONTROL_AF_TRIGGER_START == afState) {
                    if (areWeFocused) {
                        //Run specific task here
                    }
                }
                if (CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED == afState) {
                    areWeFocused = true;
                } else {
                    areWeFocused = false;
                }

                break;
            }
        }
    }

   @Override
    public void onCaptureProgressed(CameraCaptureSession session, CaptureRequest request,
                                    CaptureResult partialResult) {
        process(partialResult);
    }

    @Override
    public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request,
                                   TotalCaptureResult result) {
        process(result);
    }
};

效果不错:)