当我显示相机预览时,它会拉伸所以,我搜索并找到了一些东西。但它不能很好地运作。我正在使用surfaceView
进行显示预览。
这是我正在使用的代码。
getOptimalPreviewSize
private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
final double ASPECT_TOLERANCE = 0.1;
double targetRatio=(double)h / w;
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);
}
}
}
Log.i(TAG, "width = "+ optimalSize.width +" height = "+ optimalSize.height);
return optimalSize;
}
surfaceChanged
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.i(TAG, "surfaceChanged : width = "+width +" height = "+height);
if (mSupportedPreviewSizes != null) {
Log.i(TAG, "mSupportedPreviewSizes");
// Get Optimal Preview Size
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
// Setting the optimal preview for best result
if(mPreviewSize != null) {
Log.i(TAG, "Activate Optimal Preview");
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
mCamera.setParameters(parameters);
mCamera.startPreview();
}
}h
}
日志
surfaceChanged : width = 720 height = 1134
optimalPreviewSize width = 800 height = 480
如您所见,width
和height
不相同,我认为这就是为什么这不是显示预览效果好的原因。我能为此做些什么我是android的新手。
答案 0 :(得分:1)
我发现了一个错误:
if (Math.abs(size.height - targetHeight) < minDiff) {
相机预览尺寸为横向布局尺寸。所以size.height实际上是设备宽度。但targetHeight是视图高度(通常视图是设备大小)。 修复
targetHeight = Math.min(w, h)
你可以找到谷歌演示代码GoogleDemoCode