Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Method;

import java.util.List;

import android.hardware.Camera;

public class Main {
    public static final int DEFAULT_ZOOM_RATIO = 100;

    /** Attempts to set the camera's zoom ratio as close as possible to the given value.
     * Like the Camera.Parameters.getZoomRatios method, values are in 1/100s so 100 is unzoomed.
     * Returns the actual ratio set, which will be 100 if the camera doesn't support zoom.
     */
    public static int setCameraZoomRatio(Camera camera, int ratio) {
        if (!sdkSupportsCameraZoom())
            return DEFAULT_ZOOM_RATIO;
        try {
            Camera.Parameters params = camera.getParameters();
            Method getZoomRatios = params.getClass().getMethod("getZoomRatios");
            @SuppressWarnings("unchecked")
            List<Integer> zoomRatios = (List<Integer>) getZoomRatios.invoke(params);
            int index = zoomIndexForTargetRatio(zoomRatios, ratio);
            Method setZoom = params.getClass().getMethod("setZoom", int.class);
            setZoom.invoke(params, index);
            camera.setParameters(params);
            return zoomRatios.get(index);
        } catch (Exception ex) {
            return DEFAULT_ZOOM_RATIO;
        }
    }

    static boolean sdkSupportsCameraZoom() {
        return (android.os.Build.VERSION.SDK_INT >= 8);
    }

    /** Given a list of zoom ratios, returns the index which is closest to the given target ratio. If
     * an exact match is not possible, returns the index of the next largest or smallest value,
     * depending on which one is closer.
     */
    static int zoomIndexForTargetRatio(List<Integer> zoomRatios, int targetRatio) {
        int nratios = zoomRatios.size();
        // check for target ratio >= max or <= min
        if (zoomRatios.get(0) >= targetRatio) {
            return 0;
        }
        if (zoomRatios.get(nratios - 1) <= targetRatio) {
            return nratios - 1;
        }
        // yes, we should use binary search here
        int index = 0;
        while (zoomRatios.get(index) < targetRatio) {
            index++;
        }
        // exact match?
        if (index == 0 || zoomRatios.get(index) == targetRatio) {
            return index;
        }
        // overshot, check previous
        int underDiff = targetRatio - zoomRatios.get(index - 1);
        int overDiff = zoomRatios.get(index) - targetRatio;
        return (underDiff < overDiff) ? index - 1 : index;
    }
}