Sample Code Snippet:
public static int getOptimalPreviewSize(Activity currentActivity, Point[] sizes, double targetRatio) {
final int MAX_ASPECT_HEIGHT = 1080;
// Limiting to 1080p // Use a very small tolerance because we want an exact match.
final double ASPECT_TOLERANCE = 0.01; // -> Tolerance value set
if (sizes == null) return -1;
int optimalSizeIndex = -1;
double minDiff = Double.MAX_VALUE;
//get the screen size.
Point point = getDefaultDisplaySize(currentActivity, new Point());
int targetHeight = Math.min(point.x, point.y);
// Try to find an size match aspect ratio and size
for (int i = 0; i < sizes.length; i++) {
Point size = sizes[I];
double ratio = (double) size.x / size.y;
if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
// Count sizes with height <= 1080p to mimic camera1 api behavior.
if (size.y > MAX_ASPECT_HEIGHT) continue; // ->Checking for Height
double heightDiff = Math.abs(size.y - targetHeight);
if (heightDiff < minDiff) {
optimalSizeIndex = I;
minDiff = Math.abs(size.y - targetHeight);
} else if (heightDiff == minDiff) {
// Prefer resolutions smaller-than-display when an equally close
// larger-than-display resolution is available
if (size.y < targetHeight) {
optimalSizeIndex = I;
minDiff = heightDiff;
}
}
}
// Cannot find the one match the aspect ratio.
if (optimalSizeIndex == -1) {
Log.w(TAG, "No preview size match the aspect ratio");
minDiff = Double.MAX_VALUE;
for (int i = 0; i < sizes.length; i++) {
Point size = sizes[I];
if (Math.abs(size.y - targetHeight) < minDiff) {
optimalSizeIndex = I;
minDiff = Math.abs(size.y - targetHeight);
}
}
}
return optimalSizeIndex;
}