安卓(Android) 怎么根据用于显示此预览的布局计算相机(Camera)预览的最佳大小

2019年10月27日22:42:48安卓(Android) 怎么根据用于显示此预览的布局计算相机(Camera)预览的最佳大小已关闭评论 306 1135字阅读3分47秒

1.简介

安卓(Android) 怎么根据用于显示此预览的布局计算相机(Camera)预览的最佳大小?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


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) {
            
            layoutHeight = layoutHeight + layoutWidth;
            layoutWidth = layoutHeight - layoutWidth;
            layoutHeight = layoutHeight - layoutWidth;
        }
        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;
    }
}

 
继续阅读