安卓(Android) 怎么按高度和宽度获得最佳预览大小

2019年10月27日22:34:51安卓(Android) 怎么按高度和宽度获得最佳预览大小已关闭评论 458 865字阅读2分53秒

1.简介

安卓(Android) 怎么按高度和宽度获得最佳预览大小?——请看下文。

2.示例代码

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

 


import android.hardware.Camera;
import android.hardware.Camera.Size;

import java.util.List;

public class Main {
    public static Camera.Size getBestPreviewSize(List<Camera.Size> sizes,
            int height, int width) {
        final double ASPECT_TOLERANCE = 0.2;
        double targetRatio = (double) height / width;
        if (sizes == null)
            return null;

        Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = height;

        
        for (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 (Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }
}

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