我正在开发一个应用程序,它正在在SurfaceView
上绘制摄像头。一开始,我遇到了视图显示不正确的问题。因此,我使用了以下方法来纠正纵横比问题:
注意:这种方法被发现在多个地方用于解决Android相机的宽高比问题。
private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio;
// Check wheter is portrait or landscape
if (orientation == 1)
targetRatio = (double) h / w;
else
targetRatio = (double) w / h;
if (sizes == null)
return null;
Size optimalSize = null;
double minDiff = Double.MAX_VALUE;
int targetHeight = h;
// Try to find an size match aspect ratio and size
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);
}
}
// Cannot find the one match the aspect ratio, ignore the requirement
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;
}
这个方法在我的相机上运行得非常好,而且相机也被正确显示了。但是我在新设备上发现了问题,例如LG G3。它的分辨率被认为是最合适的,但是在纵向模式下,它会显示带有柱形黑边的图像,就像下面展示的图片一样: