i want to implement tap to focus feature in my custom camera. This is the basic code provided by Google https://github.com/googlesamples/android-Camera2Basic
Here's the code snippet where i think i should add my feature If anyone has implemented the Camera2 API please help!
private void lockFocus() {
try {
// This is how to tell the camera to lock focus.
mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
CameraMetadata.CONTROL_AF_TRIGGER_START);
// Tell #mCaptureCallback to wait for the lock.
mState = STATE_WAITING_LOCK;
mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback,
mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
Use this metering rectangles to set the CaptureRequest.CONTROL_AF_REGION & CaptureRequest.CONTROL_AE_REGION
set the CaptureRequest.CONTROL_AF_MODE to CaptureRequest.CONTROL_AF_MODE_AUTO
CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER to CameraMetadata.CONTROL_AE_TRIGGER_START
Then build capture request
Here you can find a full example.
You'll need to set the autofocus and auto-exposure region to the area tapped by the user.
The keys are CONTROL_AF_REGIONS and CONTROL_AE_REGIONS.
The units for them are in the sensor active array coordinate system, so you'll have to translate from your UI touch coordinates to coordinates relative to your preview view, and from there, to the active array coordinates.
If the aspect ratio of your preview matches that of the sensor, then that's straightforward; if not, you'll have to adjust for the crop that is done to create the preview output. The best diagram for how the cropping works is currently here. Note that if you're also applying zoom, you'll want to include the zoom factor as well in your calculations.
Once you've calculated the region, you'll probably want to set the AF mode to AUTO (instead of CONTINUOUS_PICTURE which is usually used for normal preview), and then trigger AF. Once you converge AF (look at the AF state in the capture results, wait for AF_STATE_FOCUSED_LOCKED), you're good to take a picture that's in focus. If you want to return to normal operation after some time or the user cancels the touch to focus, switch AF mode back to CONTINUOUS_PICTURE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With