csdn
问题
安卓camera1在预览时,预览画面看起来被拉伸了.
如图,圆形的盖子,变成椭圆形了.
代码
默认流程,如下为大致的打开摄像头并进行预览显示的代码文章来源:https://www.toymoban.com/news/detail-639984.html
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 size
for (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 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;
}
- 实测可用方法
把摄像头预览大小设置成屏幕显示大小,在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原创谢绝转载文章来源地址https://www.toymoban.com/news/detail-639984.html
到了这里,关于Android Camera预览画面变形问题的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!