安卓(Android) 怎么使用循环获得最佳预览大小

2019年10月27日22:34:44安卓(Android) 怎么使用循环获得最佳预览大小已关闭评论 241 1011字阅读3分22秒

1.简介

安卓(Android) 怎么使用循环获得最佳预览大小?——请看下文。

2.示例代码

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


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

public class Main {
    public static Camera.Size getOptimalPreviewSize(
            Camera.Parameters parameters, Camera.Size pictureSize) {

        if (parameters == null || pictureSize == null) {
            return null;
        }

        List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
        final double ASPECT_TOLERANCE = 0.05;
        double targetRatio = (double) pictureSize.width
                / pictureSize.height;
        if (sizes == null)
            return null;

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;
        int targetHeight = pictureSize.height;
        
        for (Camera.Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)
                continue;
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        
        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }

        return optimalSize;
    }
}

 
继续阅读
编程十万个怎么办