Determine the optimal width and height, based on max size and optimal choice - Android android.hardware

Android examples for android.hardware:Camera Size

Description

Determine the optimal width and height, based on max size and optimal choice

Demo Code


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.SensorManager;
import android.hardware.Camera.Size;
import android.view.OrientationEventListener;
import android.view.SurfaceView;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;

public class Main{

    public static WidthHeight getBestWidthHeight(List<Size> sizes,
            WidthHeight maxWH, WidthHeight optWH) {

        // check if none
        if (sizes.isEmpty())
            return null;

        // loop through possible ones and find the ones that are below the max
        ArrayList<Size> belowMax = new ArrayList<Size>();
        for (Iterator<Size> it = sizes.iterator(); it.hasNext();) {
            Size s = it.next();//from www  . j  a  v  a 2s  .c  om
            if (maxWH == null)
                belowMax.add(s);
            else if (s.width <= maxWH.width && s.height <= maxWH.height)
                belowMax.add(s);
        }

        // check if none
        if (belowMax.isEmpty())
            return null;

        // function to check optimal is diff(width)^2 + diff(height)^2, and aspect ratio is 10x more important
        WidthHeight result = new WidthHeight(0, 0);
        double fitness = 1e12;
        double tmpFitness;
        for (Iterator<Size> it = belowMax.iterator(); it.hasNext();) {
            Size s = it.next();
            tmpFitness = (double) Math.sqrt(Math.pow(s.width - optWH.width,
                    2) + Math.pow(s.height - optWH.height, 2))
                    / (optWH.height * .5 + optWH.width * .5)
                    + Math.abs((double) optWH.width / optWH.height
                            - (double) s.width / s.height) * 10;
            if (tmpFitness < fitness) {
                fitness = tmpFitness;
                result.width = s.width;
                result.height = s.height;
            }
        }

        if (result.width == 0 && result.height == 0)
            result = null;

        return result;
    }
}

Related Tutorials