Calculate the optimal size of camera preview according to layout used to display this preview - Android Camera

Android examples for Camera:Camera Preview

Description

Calculate the optimal size of camera preview according to layout used to display this preview

Demo Code


//package com.java2s;
import android.hardware.Camera;
import java.util.List;

public class Main {
    private static final double ASPECT_TOLERANCE = 0.15;

    public static Camera.Size getBestPreviewSize(List<Camera.Size> sizes,
            int layoutWidth, int layoutHeight, boolean isPortrait) {
        if (isPortrait) {
            // Inverse surfaceWidth and surfaceHeight since the sizes are all in landscape mode.
            layoutHeight = layoutHeight + layoutWidth;
            layoutWidth = layoutHeight - layoutWidth;
            layoutHeight = layoutHeight - layoutWidth;
        }/*from www  .j  a v  a 2s .  co m*/
        double targetRatio = (double) layoutWidth / layoutHeight;
        Camera.Size optimalSize = null;
        double optimalArea = 0;

        for (Camera.Size candidateSize : sizes) {
            double candidateRatio = (double) candidateSize.width
                    / candidateSize.height;
            double candidateArea = candidateSize.width
                    * candidateSize.height;
            double ratioDifference = Math.abs(candidateRatio - targetRatio);
            if (ratioDifference < ASPECT_TOLERANCE
                    && candidateArea > optimalArea) {
                optimalSize = candidateSize;
                optimalArea = candidateArea;
            }
        }

        if (optimalSize == null) {
            optimalArea = 0;
            for (Camera.Size candidateSize : sizes) {
                double candidateArea = candidateSize.width
                        * candidateSize.height;
                if (candidateArea > optimalArea) {
                    optimalSize = candidateSize;
                    optimalArea = candidateArea;
                }
            }
        }

        return optimalSize;
    }
}

Related Tutorials