Get the Camera optimal preview size for the given screen size. - Android Phone

Android examples for Phone:Camera

Description

Get the Camera optimal preview size for the given screen size.

Demo Code


//package com.java2s;

import java.util.Iterator;
import java.util.List;
import android.hardware.Camera.Size;

public class Main {
    private final static double epsilon = 0.17;

    /**// ww w .  j  a  va 2s . co m
     * Get the optimal preview size for the given screen size.
     * @param sizes
     * @param screenWidth
     * @param screenHeight
     * @return
     */
    public static Size getOptimalPreviewSize(List<Size> sizes,
            int screenWidth, int screenHeight) {
        double aspectRatio = ((double) screenWidth) / screenHeight;
        Size optimalSize = null;
        for (Iterator<Size> iterator = sizes.iterator(); iterator.hasNext();) {
            Size currSize = iterator.next();
            double curAspectRatio = ((double) currSize.width)
                    / currSize.height;
            //do the aspect ratios equal?
            if (Math.abs(aspectRatio - curAspectRatio) < epsilon) {
                //they do
                if (optimalSize != null) {
                    //is the current size smaller than the one before
                    if (optimalSize.height > currSize.height
                            && optimalSize.width > currSize.width) {
                        optimalSize = currSize;
                    }
                } else {
                    optimalSize = currSize;
                }
            }
        }
        if (optimalSize == null) {
            //did not find a size with the correct aspect ratio.. let's choose the smallest instead
            for (Iterator<Size> iterator = sizes.iterator(); iterator
                    .hasNext();) {
                Size currSize = iterator.next();
                if (optimalSize != null) {
                    //is the current size smaller than the one before
                    if (optimalSize.height > currSize.height
                            && optimalSize.width > currSize.width) {
                        optimalSize = currSize;
                    } else {
                        optimalSize = currSize;
                    }
                } else {
                    optimalSize = currSize;
                }

            }
        }
        return optimalSize;
    }
}

Related Tutorials