Set the camera focus area in Android

PerracoLabs picture PerracoLabs · Jul 31, 2013 · Viewed 25.4k times · Source

following several tutorials and examples I came up with the next algorithm to set the camera focus on a specific spot, the problem is that the camera completely ignores the spot and performs a normal overall focus instead of the rect area which I have specified. Is there anything else that I am missing in the algorithm? This has been tested on several phones all with Android 4.0 and above, so the focus area API is supported on these devices. Note, the app I am writing works in landscape mode only.

@Override
public boolean onTouchEvent(final MotionEvent event)
{
    if (event.getAction() == MotionEvent.ACTION_UP)
    {
        float x = event.getX();
        float y = event.getY();
        float touchMajor = event.getTouchMajor();
        float touchMinor = event.getTouchMinor();

        Rect touchRect = new Rect((int)(x - touchMajor / 2), (int)(y - touchMinor / 2), (int)(x + touchMajor / 2), (int)(y + touchMinor / 2));

        this.submitFocusAreaRect(touchRect);
    }
}

private void submitFocusAreaRect(final Rect touchRect)
{
    Camera.Parameters cameraParameters = camera.getParameters();

    if (cameraParameters.getMaxNumFocusAreas() == 0)
    {
        return;
    }

    // Convert from View's width and height to +/- 1000

    Rect focusArea = new Rect();

    focusArea.set(touchRect.left * 2000 / cameraSurfaceView.getWidth() - 1000, 
                      touchRect.top * 2000 / cameraSurfaceView.getHeight() - 1000,
                      touchRect.right * 2000 / cameraSurfaceView.getWidth() - 1000,
                      touchRect.bottom * 2000 / cameraSurfaceView.getHeight() - 1000);

    // Submit focus area to camera

    ArrayList<Camera.Area> focusAreas = new ArrayList<Camera.Area>();
    focusAreas.add(new Camera.Area(focusArea, 1000));

    cameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
    cameraParameters.setFocusAreas(focusAreas);
    camera.setParameters(cameraParameters);

    // Start the autofocus operation

    camera.autoFocus(this);
}

Answer

npace picture npace · Jul 31, 2013

before cameraParameters.setFocusAreas(focusAreas);, you should add this:

cameraParameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);