csdn
问题
安卓camera1在预览时,预览画面看起来被拉伸了.
如图,圆形的盖子,变成椭圆形了.
代码
默认流程,如下为大致的打开摄像头并进行预览显示的代码
private Camera mCamera = null;
private SurfaceView mSurfaceView = null;
private SurfaceHolder holder = null;mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
holder = mSurfaceView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);mCamera = Camera.open(mCameraId);
// .... 中间设置方向等省略
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
解决
- 网上大部分的解决方法(实测不一定有效)
原理是遍历摄像头分辨率,找到与当前屏幕契合的分辨率,并设置为预览大小.
如下代码,getOptimalPreviewSize的调用放在上面的mCamera.startPreview();之前.
Camera.Parameters parameters = null;
parameters = mCamera.getParameters();
DisplayMetrics dm = getResources().getDisplayMetrics();
List<Size> previewSizes = parameters.getSupportedPreviewSizes();
Size previewSize = getOptimalPreviewSize(previewSizes, dm.widthPixels, dm.heightPixels);
parameters.setPreviewSize(previewSize.width, previewSize.height);private Size getOptimalPreviewSize(List<Size> sizes, int w, int h) {final double ASPECT_TOLERANCE = 0.1;double 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 sizefor (Size size : sizes) {double ratio = (double) size.width / size.height;if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE)continue;int tempDiff = Math.abs(size.height - targetHeight);if (tempDiff < minDiff) {optimalSize = size;minDiff = tempDiff;}}// Cannot find the one match the aspect ratio, ignore the requirementif (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;
}
- 实测可用方法
把摄像头预览大小设置成屏幕显示大小,在mCamera.startPreview()调用如下代码
public static void setCameraPreviewSize(Camera camera) {WindowManager manager = (WindowManager) FactoryTestApplication.getContext().getSystemService(Context.WINDOW_SERVICE);Display display = manager.getDefaultDisplay();Parameters parameters = camera.getParameters();parameters.setPreviewSize(display.getHeight(), display.getWidth());camera.setParameters(parameters);
}
显示正常图如下
作者:帅得不敢出门 csdn原创谢绝转载