Android自定义相机过程中经常遇到相机预览画面拉伸的问题,这种情况是因为预览控件比例与当前相机预览分辨率比例不一致导致的,想要预览画面正常就要找到与预览控件比例最接近的相机预览分辨率,这里记录一下Camera获取最佳预览分辨率的方法
/**
* 获取最佳预览分辨率,解决预览拉伸问题
*
* @param supportedSize 相机支持的预览分辨率
* @param screenResolution 控件宽高或屏幕宽高
* @return 与预览控件比例最接近预览分辨率
*/
private static Point findClosestPreviewSizeValue(List<Size> supportedSize, Point screenResolution) {
// 如果x<y,交换x,y的值
if (screenResolution.x < screenResolution.y) {
int temp = screenResolution.x;
screenResolution.x = screenResolution.y;
screenResolution.y = temp;
}
// 计算控件宽高比
float referRatio = screenResolution.x * 1.0f / screenResolution.y;
float lastDiff = 0.5f;
Size lastSize = null;
for (Size size : supportedSize) {
// 只找出预览高度>=720 分辨率
if (size.height < 720) {
continue;
}
// 计算分辨率宽高比
float supportRatio = size.width * 1.0f / size.height;
// 计算差值的绝对值
float currentDiff = Math.abs(referRatio - supportRatio);
// 循环取出差值最小的分辨率
if (currentDiff < lastDiff) {
lastDiff = currentDiff;
lastSize = size;
}
}
return new Point(lastSize.width, lastSize.height);
}