如何将相机焦点锁定在我在camera2 api中点击照片的位置

时间:2017-10-26 10:28:53

标签: android camera android-camera2

我知道here之前已经问过这类问题。但是我无法理解我的情况应该怎样做。所以我想做的是显示点击的照片,并在我点击照片时停止相机预览,每当再次按下相机按钮我想再次显示预览。这是我拍照的方式

private void takePhoto() {
    try {
        CaptureRequest.Builder request = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        request.addTarget(jpegSurface);
        request.set(CaptureRequest.STATISTICS_LENS_SHADING_MAP_MODE, CaptureRequest.STATISTICS_LENS_SHADING_MAP_MODE_ON);

        imageCaptured = true;
        lockFocus();
        session.capture(request.build(), new CameraCaptureSession.CaptureCallback() {
            @Override
            public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
                Toast.makeText(getBaseContext(), "captured..", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCaptureFailed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureFailure failure) {
                unLockFocus();
                imageCaptured=false;
            }
        }, null);

    } catch (CameraAccessException e) {
        Toast.makeText(this, "Unable to click photo", Toast.LENGTH_SHORT).show();

    }
}

这是预览代码

 private void startCamera() {
    try {
        requestPreview = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        requestPreview.set(CaptureRequest.CONTROL_AF_MODE,CaptureRequest.CONTROL_AF_MODE_AUTO);
        requestPreview.addTarget(textureSurface);
        session.setRepeatingRequest(requestPreview.build(), null, null);
    } catch (CameraAccessException e) {
        Toast.makeText(this, "Unable to create preview", Toast.LENGTH_SHORT).show();

    }
}

以下是我如何锁定和解锁焦点

    private void lockFocus() {
    requestPreview.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START);
    try {
        session.capture(requestPreview.build(), null, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

private void unLockFocus() {
    scanButton.setText("SCAN");
    imageCaptured = false;
    requestPreview.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_CANCEL);
    try {
        session.setRepeatingRequest(requestPreview.build(), null, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

 cameraButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (imageCaptured) {
                unLockFocus();
                return;
            }
            takePhoto();
        }
    });

但是这段代码的问题在于它会将焦点锁定几秒钟,然后再次启动相机预览。由于CaptureRequest.CONTROL_AF_TRIGGER_STARTCaptureRequest.CONTROL_AF_TRIGGER_CANCEL,可能会发生这种情况。如果这是原因,那么我可以使用什么而不是这个。

0 个答案:

没有答案