安卓(Android) 怎么在支持的相机(Camera)预览大小上迭代,以查看哪个最适合给定视图的尺寸,同时保持纵横比

2019年10月27日22:41:00安卓(Android) 怎么在支持的相机(Camera)预览大小上迭代,以查看哪个最适合给定视图的尺寸,同时保持纵横比已关闭评论 264 916字阅读3分3秒

1.简介

安卓(Android) 怎么在支持的相机(Camera)预览大小上迭代,以查看哪个最适合给定视图的尺寸,同时保持纵横比?——请看下文。

2.示例代码

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

import android.hardware.Camera;
import android.util.Log;

public class Main {
  private static final String TAG = "";

  public static Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes,
      int w, int h) {
    final double ASPECT_TOLERANCE = 0.1;
    double targetRatio = (double) w / h;
    if (sizes == null)
      return null;

    Camera.Size optimalSize = null;

    double minDiff = Double.MAX_VALUE;

    int targetHeight = h;

    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;
  }
}

 
继续阅读