相机预览被拉伸和倾斜
Posted
技术标签:
【中文标题】相机预览被拉伸和倾斜【英文标题】:Camera Preview is stretched and skewed 【发布时间】:2016-08-12 21:35:35 【问题描述】:如何解决我的相机预览中的图像拉伸问题?
相机预览类
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback
private SurfaceHolder mHolder;
private Camera mCamera;
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraPreview(Context context, Camera camera)
super(context);
mCamera = camera;
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
public void surfaceCreated(SurfaceHolder holder)
try
// create the surface and start camera preview
if (mCamera == null)
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
catch (IOException e)
Log.d(VIEW_LOG_TAG,
"Error setting camera preview: " + e.getMessage());
public void refreshCamera(Camera camera)
if (mHolder.getSurface() == null)
// preview surface does not exist
return;
// stop preview before making changes
try
mCamera.stopPreview();
catch (Exception e)
// ignore: tried to stop a non-existent preview
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
setCamera(camera);
try
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
catch (Exception e)
Log.d(VIEW_LOG_TAG,
"Error starting camera preview: " + e.getMessage());
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
refreshCamera(mCamera);
public void setCamera(Camera camera)
// method to set a camera instance
mCamera = camera;
@Override
public void surfaceDestroyed(SurfaceHolder holder)
// TODO Auto-generated method stub
// mCamera.release();
【问题讨论】:
注意在 Grafika 中使用 AspectFrameLayout,例如“连续捕获”(github.com/google/grafika/blob/master/src/com/android/grafika/…)。 FWIW,当您的图像被拉伸时,我会很惊讶它被歪斜,因为源和目标都是矩形。 【参考方案1】:可能您的 CameraView 的纵横比与相机预览大小的纵横比不匹配。
您应该计算您的 CameraView 的纵横比并使用此纵横比来找到 Camera.Parameters.setPreviewSize()
方法的最佳尺寸。
试试这个
private Camera.Size getBestPreviewSize(Camera.Parameters parameters, int width, int height)
Camera.Size result = null;
double ratio = width / height;
double w = 0, h = 0;
for (Camera.Size size : parameters.getSupportedPreviewSizes())
w = size.width;
h = size.height;
if (w / h == ratio)
if (result != null)
if (w > result.width)
result = size;
else
result = size;
return (result);
【讨论】:
在哪里调用这个方法?以及如何检查我的预览的大小? 首先,您需要在开始预览之前调用该方法。您可以搜索“如何设置我的相机预览大小”以查看步骤。其次,您的预览大小是您在屏幕上显示的 SurfaceView 的大小。最后,fadden 的建议是另一种方式。以上是关于相机预览被拉伸和倾斜的主要内容,如果未能解决你的问题,请参考以下文章