安卓(Android) 怎么根据目标纵横比和大小选择最佳预览大小

2019年10月27日22:35:34安卓(Android) 怎么根据目标纵横比和大小选择最佳预览大小已关闭评论 367 1241字阅读4分8秒

1.简介

安卓(Android) 怎么根据目标纵横比和大小选择最佳预览大小?——请看下文。

2.示例代码

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

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Size;
import android.view.Surface;
import java.util.List;

public class Main{
    
    private static final double PREVIEW_ASPECT_RATIO_TOLERANCE = 0.1d;
    
    public static Size getOptimalPreviewSize(List<Size> previewSizes,
            int targetWidth, int targetHeight) {
        
        if (previewSizes == null || previewSizes.isEmpty()) {
            return null;
        }

        Size optimalSize = null;

        double targetAspectRatio = (double) targetWidth / targetHeight;
        int minDiff = Integer.MAX_VALUE;

        
        for (Size size : previewSizes) {
            
            double aspectRatio = (double) size.width / size.height;
            if (Math.abs(aspectRatio - targetAspectRatio) > PREVIEW_ASPECT_RATIO_TOLERANCE) {
                continue;
            }

            int diff = Math.max(Math.abs(size.width - targetWidth),
                    Math.abs(size.height - targetHeight));
            if (diff < minDiff) {
                optimalSize = size;
                minDiff = diff;
            }
        }

        
        if (optimalSize == null) {
            minDiff = Integer.MAX_VALUE;
            for (Size size : previewSizes) {
                int diff = Math.max(Math.abs(size.width - targetWidth),
                        Math.abs(size.height - targetHeight));
                if (diff < minDiff) {
                    optimalSize = size;
                    minDiff = diff;
                }
            }
        }

        LogsHelper.slog(CameraHelper.class, "getOptimalPreviewSize",
                "size=[" + optimalSize.width + ", " + optimalSize.height
                        + "]");

        return optimalSize;
    }
}

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