Search code examples
androidcameracamera2

Android camera2 tap to focus


Trying to implement tap to focus using camera2api.

    CaptureRequest.Builder afBuilder = mPreviewBuilder;

    Rect newRect=new Rect(0,0,200,200);
    MeteringRectangle meteringRectangle=new MeteringRectangle(newRect,METERING_WEIGHT_DONT_CARE);

    MeteringRectangle[] areas = afBuilder.get(CaptureRequest.CONTROL_AF_REGIONS);

    mPreviewBuilder.set(CaptureRequest.CONTROL_AF_REGIONS,areas);
    mPreviewBuilder.set(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_AUTO);
    mPreviewBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_START);
    mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), mCaptureCallback, mBackgroundHandler);

In my call back I am continuously getting stuck in an ACTIVE_SCAN state and occasionally goes into FOCUS_NOT_LOCKED state. I can never seem to get into a FOCUS_LOCKED state and the preview never look focused.

Using a samsung galaxy note 3.


Solution

  • For one, you're not actually setting an AF region - you're just reusing the default region from mPreviewBuilder.

    Second, even if you set the region to [(0,0,200,200), METERING_WEIGHT_DONT_CARE], that's the top-left corner of the image, and probably not what you want?

    Third, and most importantly, you're setting the AF trigger to be repeating. This means that on every frame, you're asking the camera to restart focusing. So it will never complete, because you never let it.

    You need to set AF_TRIGGER to START for only a single capture; you'll still want to set the AF_REGION and AF_MODE on repeating request to be consistent through the whole AF scan you're starting.