我一直在努力使Android上的我的自定义相机的活动,但旋转相机时,表面视图的纵横比得到弄糟。
在我的OnCreate的活动,我把它认为显示摄像机的参数表面视图的FrameLayout。
//FrameLayout that will hold the camera preview
FrameLayout previewHolder = (FrameLayout) findViewById(R.id.camerapreview);
//Setting camera's preview size to the best preview size
Size optimalSize = null;
camera = getCameraInstance();
double aspectRatio = 0;
if(camera != null){
//Setting the camera's aspect ratio
Camera.Parameters parameters = camera.getParameters();
List<Size> sizes = parameters.getSupportedPreviewSizes();
optimalSize = CameraPreview.getOptimalPreviewSize(sizes, getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels);
aspectRatio = (float)optimalSize.width/optimalSize.height;
}
if(optimalSize!= null){
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)(getResources().getDisplayMetrics().widthPixels*aspectRatio));
previewHolder.setLayoutParams(params);
LayoutParams surfaceParams = new LayoutParams(LayoutParams.MATCH_PARENT, (int)(getResources().getDisplayMetrics().widthPixels*aspectRatio));
cameraPreview.setLayoutParams(surfaceParams);
}
cameraPreview.setCamera(camera);
//Adding the preview to the holder
previewHolder.addView(cameraPreview);
然后,在表面观我设置相机的参数来显示
public void setCamera(Camera camera) {
if (mCamera == camera) { return; }
mCamera = camera;
if (mCamera != null) {
requestLayout();
try {
mCamera.setPreviewDisplay(mHolder);
} catch (IOException e) {
e.printStackTrace();
}
if(mCamera != null){
//Setting the camera's aspect ratio
Camera.Parameters parameters = mCamera.getParameters();
List<Size> sizes = parameters.getSupportedPreviewSizes();
Size optimalSize = getOptimalPreviewSize(sizes, getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels);
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
mCamera.setParameters(parameters);
}
/*
Important: Call startPreview() to start updating the preview surface. Preview must
be started before you can take a picture.
*/
mCamera.startPreview();
}
}
你可以看到,乐高的人长高和瘦的时候,手机旋转:
我如何能确保我的相机视图的纵横比是正确的?
Answer 1:
我用这个方法 - >基于API演示让我的预览大小:
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);
}
}
}
return optimalSize;
}
正如你所看到的,你必须输入宽度和屏幕的高度。 该方法将基于这样的价值观,然后从supportedPreviewSizes列表中会选择最适合你的avaliable那些计算的屏幕比例。 让您supportedPreviewSize列表地方Camera对象不以空
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
然后在onMeasure你可以得到你这样的最佳previewSize:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
if (mSupportedPreviewSizes != null) {
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
}
然后(在我surfaceChanged方法的代码,就像我说我使用的CameraActivity代码API演示结构,你可以在Eclipse中生成它):
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
mCamera.setParameters(parameters);
mCamera.startPreview();
而一个提示你,因为我几乎没有像你一样的应用程序。 相机活动的良好做法是隐藏状态栏。 像Instagram的应用程序正在这样做。 它减少了屏幕高度值,改变你的比值。 这是可能得到一些设备上奇怪的预览大小(你SurfaceView将被削减一点点)
而要回答你的问题,如何检查,如果你的预览比例是正确的? 然后得到的,你在设置参数的高度和宽度:
mCamera.setParameters(parameters);
您的组比等于高度/宽度。 屏幕如果你想相机好看你的屏幕上,然后,你设定相机必须是相同的高度(减去状态栏)参数高度/宽度比/宽比。
Answer 2:
F1Sher的解决方案是好的,但有时无法正常工作。 特别是,当你的surfaceView没有覆盖整个屏幕。 在这种情况下,你需要重写onMeasure()方法。 我在这里复制我的代码,供大家参考。
由于我基于宽度测量surfaceView然后,我有我的屏幕我设计充满它的结束点点白色的差距。 你可以,如果你保持高度和宽度加乘它比来解决这个问题。 然而,它会稍微压扁surfaceView。
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private static final String TAG = "CameraPreview";
private Context mContext;
private SurfaceHolder mHolder;
private Camera mCamera;
private List<Camera.Size> mSupportedPreviewSizes;
private Camera.Size mPreviewSize;
public CameraPreview(Context context, Camera camera) {
super(context);
mContext = context;
mCamera = camera;
// supported preview sizes
mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();
for(Camera.Size str: mSupportedPreviewSizes)
Log.e(TAG, str.width + "/" + str.height);
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
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) {
// empty. surfaceChanged will take care of stuff
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
Log.e(TAG, "surfaceChanged => w=" + w + ", h=" + 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.
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
try {
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
mCamera.setParameters(parameters);
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
if (mSupportedPreviewSizes != null) {
mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
}
if (mPreviewSize!=null) {
float ratio;
if(mPreviewSize.height >= mPreviewSize.width)
ratio = (float) mPreviewSize.height / (float) mPreviewSize.width;
else
ratio = (float) mPreviewSize.width / (float) mPreviewSize.height;
// One of these methods should be used, second method squishes preview slightly
setMeasuredDimension(width, (int) (width * ratio));
// setMeasuredDimension((int) (width * ratio), height);
}
}
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.height / size.width;
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);
}
}
}
return optimalSize;
}
}
Answer 3:
注:我的解决方案HESAM的解决方案的延续: https://stackoverflow.com/a/22758359/1718734
我地址:Hesam的说有在某些手机上,这样可能会出现一个白色的小空间:
Hesam提出了第二种方案,但squishes预览。 而在某些设备上,它在很大程度上扭曲了。
那么,我们如何解决这个问题。 这是简单...通过,直到它在屏幕填充纵横比相乘。 我注意到,一些流行的应用程序,如Snapchat,WhatsApp的,等的工作方式相同。
所有你需要做的就是将其添加到onMeasure方法:
float camHeight = (int) (width * ratio);
float newCamHeight;
float newHeightRatio;
if (camHeight < height) {
newHeightRatio = (float) height / (float) mPreviewSize.height;
newCamHeight = (newHeightRatio * camHeight);
Log.e(TAG, camHeight + " " + height + " " + mPreviewSize.height + " " + newHeightRatio + " " + newCamHeight);
setMeasuredDimension((int) (width * newHeightRatio), (int) newCamHeight);
Log.e(TAG, mPreviewSize.width + " | " + mPreviewSize.height + " | ratio - " + ratio + " | H_ratio - " + newHeightRatio + " | A_width - " + (width * newHeightRatio) + " | A_height - " + newCamHeight);
} else {
newCamHeight = camHeight;
setMeasuredDimension(width, (int) newCamHeight);
Log.e(TAG, mPreviewSize.width + " | " + mPreviewSize.height + " | ratio - " + ratio + " | A_width - " + (width) + " | A_height - " + newCamHeight);
}
这将计算的屏幕的高度和获取屏幕高度和mPreviewSize高度的比率。 然后,它由新的高度比乘以相机的宽度和高度以及相应地设置测量的尺寸。
你知道接下来的事情,你结束了这一点:d
这也与他前置摄像头,效果很好。 我相信这是去是最好的方法。 现在留给我的应用程序的唯一事情就是在点击保存预览本身“捕捉”。 但是你,这是它。
Answer 4:
好了,所以我觉得这是普通摄像头预览拉伸的问题没有足够的答案 。 或者说,至少我没有找到一个。 我的应用程序也遭遇这种拉伸综合征和我花了一段时间来砌起来从这个门户网站和互联网中的所有用户答案的解决方案。
我试图@ Hesam的解决方案 ,但它没有工作,离开了我的相机预览majorly扭曲。
首先,我表明我的解决方案的代码(代码的重要组成部分),然后我解释为什么我把这些步骤。 有余地的性能改进。
主要业务XML布局:
<RelativeLayout
android:id="@+id/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<FrameLayout
android:id="@+id/camera_preview"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
摄像头预览:
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder prHolder;
private Camera prCamera;
public List<Camera.Size> prSupportedPreviewSizes;
private Camera.Size prPreviewSize;
@SuppressWarnings("deprecation")
public YoCameraPreview(Context context, Camera camera) {
super(context);
prCamera = camera;
prSupportedPreviewSizes = prCamera.getParameters().getSupportedPreviewSizes();
prHolder = getHolder();
prHolder.addCallback(this);
prHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
try {
prCamera.setPreviewDisplay(holder);
prCamera.startPreview();
} catch (IOException e) {
Log.d("Yologram", "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
if (prHolder.getSurface() == null){
return;
}
try {
prCamera.stopPreview();
} catch (Exception e){
}
try {
Camera.Parameters parameters = prCamera.getParameters();
List<String> focusModes = parameters.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
}
parameters.setPreviewSize(prPreviewSize.width, prPreviewSize.height);
prCamera.setParameters(parameters);
prCamera.setPreviewDisplay(prHolder);
prCamera.startPreview();
} catch (Exception e){
Log.d("Yologram", "Error starting camera preview: " + e.getMessage());
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
setMeasuredDimension(width, height);
if (prSupportedPreviewSizes != null) {
prPreviewSize =
getOptimalPreviewSize(prSupportedPreviewSizes, width, height);
}
}
public 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);
}
}
}
return optimalSize;
}
}
主要活动:
public class MainActivity extends Activity {
...
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
maCamera = getCameraInstance();
maLayoutPreview = (FrameLayout) findViewById(R.id.camera_preview);
maPreview = new CameraPreview(this, maCamera);
Point displayDim = getDisplayWH();
Point layoutPreviewDim = calcCamPrevDimensions(displayDim,
maPreview.getOptimalPreviewSize(maPreview.prSupportedPreviewSizes,
displayDim.x, displayDim.y));
if (layoutPreviewDim != null) {
RelativeLayout.LayoutParams layoutPreviewParams =
(RelativeLayout.LayoutParams) maLayoutPreview.getLayoutParams();
layoutPreviewParams.width = layoutPreviewDim.x;
layoutPreviewParams.height = layoutPreviewDim.y;
layoutPreviewParams.addRule(RelativeLayout.CENTER_IN_PARENT);
maLayoutPreview.setLayoutParams(layoutPreviewParams);
}
maLayoutPreview.addView(maPreview);
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private Point getDisplayWH() {
Display display = this.getWindowManager().getDefaultDisplay();
Point displayWH = new Point();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
display.getSize(displayWH);
return displayWH;
}
displayWH.set(display.getWidth(), display.getHeight());
return displayWH;
}
private Point calcCamPrevDimensions(Point disDim, Camera.Size camDim) {
Point displayDim = disDim;
Camera.Size cameraDim = camDim;
double widthRatio = (double) displayDim.x / cameraDim.width;
double heightRatio = (double) displayDim.y / cameraDim.height;
// use ">" to zoom preview full screen
if (widthRatio < heightRatio) {
Point calcDimensions = new Point();
calcDimensions.x = displayDim.x;
calcDimensions.y = (displayDim.x * cameraDim.height) / cameraDim.width;
return calcDimensions;
}
// use "<" to zoom preview full screen
if (widthRatio > heightRatio) {
Point calcDimensions = new Point();
calcDimensions.x = (displayDim.y * cameraDim.width) / cameraDim.height;
calcDimensions.y = displayDim.y;
return calcDimensions;
}
return null;
}
}
我的评论:
所有这一切的一点是,虽然你在计算出最佳的相机尺寸 getOptimalPreviewSize()
你只能挑选最接近的比例适合屏幕。 所以,除非该比率预览将延伸完全相同 。
它为什么会伸展? 因为你的FrameLayout相机预览中layout.xml设置宽度和高度match_parent。 所以这就是为什么预览会拉伸到全屏。
什么需要做是设置相机预览布局的宽度和高度,以匹配所选相机尺寸比 ,所以预览保持其宽高比和不会扭曲。
我试图用CameraPreview
类来完成所有的计算和布局的变化,但我无法弄清楚。 我尝试应用这一解决方案 ,但SurfaceView
不承认getChildCount ()
或getChildAt (int index)
。 我想,我得到它与一个参考,最终工作maLayoutPreview
,但它是行为不端和应用设置的比我的整个应用程序,它这样做第一张照片拍摄后。 所以我让他去感动的布局修改到MainActivity
。
在CameraPreview
我改变prSupportedPreviewSizes
和getOptimalPreviewSize()
以大众这样我就可以使用它MainActivity
。 然后我需要的显示尺寸 (减去如果在导航/状态栏的一个)和选择了最佳的摄像机的尺寸 。 我试图让RelativeLayout的(或FrameLayout里)的大小,而不是显示尺寸,但它返回零值。 该解决方案并没有为我工作。 布局得到后的价值onWindowFocusChanged
(在日志中选中)。
所以,我有我的用于计算布局尺寸以匹配所选摄像机尺寸的纵横比的方法。 现在,你只需要设置LayoutParams
相机预览布局。 更改宽度,高度和中心,它的母公司。
有两种选择如何计算预览尺寸。 要么你希望它适合与黑条的屏幕(如果windowBackground设置为null)在两侧或顶部/底部。 或者你想预览放大到全屏 。 我在离开注释以了解更多信息calcCamPrevDimensions()
Answer 5:
喜的是,这里并没有为我工作的getOptimalPreview(),所以我想分享我的版本:
private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
if (sizes==null) return null;
Camera.Size optimalSize = null;
double ratio = (double)h/w;
double minDiff = Double.MAX_VALUE;
double newDiff;
for (Camera.Size size : sizes) {
newDiff = Math.abs((double)size.width/size.height - ratio);
if (newDiff < minDiff) {
optimalSize = size;
minDiff = newDiff;
}
}
return optimalSize;
}
Answer 6:
只是为了让这个线程更完整的我加入我的版本的答案:
我想要的东西来实现:表面而不应该被拉伸,并应覆盖整个屏幕,而且,只有在我的应用程序风景模式。
解:
该解决方案是一个非常小的扩展F1sher的解决方案:
=>第一步是整合F1sher的溶液。
=>现在,有可能在表面视图不覆盖整个屏幕出现在F1sher的解决方案,该解决方案是使表面观比屏幕尺寸更大,使其覆盖整个屏幕,为:
size = getOptimalPreviewSize(mCamera.getParameters().getSupportedPreviewSizes(), screenWidth, screenHeight);
Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(size.width, size.height);
mCamera.setParameters(parameters);
double screenRatio = (double) screenHeight / screenWidth;
double previewRatio = (double) size.height / size.width;
if (previewRatio > screenRatio) /*if preview ratio is greater than screen ratio then we will have to recalculate the surface height while keeping the surface width equal to the screen width*/
{
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(screenWidth, (int) (screenWidth * previewRatio));
params1.addRule(RelativeLayout.CENTER_IN_PARENT);
flPreview.setLayoutParams(params1);
flPreview.setClipChildren(false);
LayoutParams surfaceParams = new LayoutParams(screenWidth, (int) (screenWidth * previewRatio));
surfaceParams.gravity = Gravity.CENTER;
mPreview.setLayoutParams(surfaceParams);
}
else /*if preview ratio is smaller than screen ratio then we will have to recalculate the surface width while keeping the surface height equal to the screen height*/
{
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams((int) ((double) screenHeight / previewRatio), screenHeight);
params1.addRule(RelativeLayout.CENTER_IN_PARENT);
flPreview.setLayoutParams(params1);
flPreview.setClipChildren(false);
LayoutParams surfaceParams = new LayoutParams((int) ((double) screenHeight / previewRatio), screenHeight);
surfaceParams.gravity = Gravity.CENTER;
mPreview.setLayoutParams(surfaceParams);
}
flPreview.addView(mPreview);
/* The TopMost layout used is the RelativeLayout, flPreview is the FrameLayout in which Surface View is added, mPreview is an instance of a class which extends SurfaceView */
Answer 7:
我想通了什么问题-它是与取向的变化。 如果更改摄像头的方向,以90度或270度比你需要交换的宽度和支持的尺寸的高度 ,一切都会好的。
也表面视图应该位于一个帧布局和具有重心。
下面是例如在C#(Xamarin):
public void SurfaceChanged(ISurfaceHolder holder, Android.Graphics.Format format, int width, int height)
{
_camera.StopPreview();
// find best supported preview size
var parameters = _camera.GetParameters();
var supportedSizes = parameters.SupportedPreviewSizes;
var bestPreviewSize = supportedSizes
.Select(x => new { Width = x.Height, Height = x.Width, Original = x }) // HACK swap height and width because of changed orientation to 90 degrees
.OrderBy(x => Math.Pow(Math.Abs(x.Width - width), 3) + Math.Pow(Math.Abs(x.Height - height), 2))
.First();
if (height == bestPreviewSize.Height && width == bestPreviewSize.Width)
{
// start preview if best supported preview size equals current surface view size
parameters.SetPreviewSize(bestPreviewSize.Original.Width, bestPreviewSize.Original.Height);
_camera.SetParameters(parameters);
_camera.StartPreview();
}
else
{
// if not than change surface view size to best supported (SurfaceChanged will be called once again)
var layoutParameters = _surfaceView.LayoutParameters;
layoutParameters.Width = bestPreviewSize.Width;
layoutParameters.Height = bestPreviewSize.Height;
_surfaceView.LayoutParameters = layoutParameters;
}
}
注意,由于原始大小(不交换)的相机参数应设置,并且表面观大小应该被交换。
Answer 8:
我想上面的所有解决方案,但没有人对我的作品。 finaly我解决了它自己,竟发现它很容易。 还有,你必须要小心两分。
parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
这previewSize必须是摄像机支持的分辨率,它可以得到如下的一个:
List<Camera.Size> rawSupportedSizes = parameters.getSupportedPreviewSizes();
通常rawSupportedSize之一等于设备分辨率。
第二,请将SurfaceView在的FrameLayout和设置表面布局的高度和宽度在surfaceChanged方法如上
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) surfaceView.getLayoutParams();
layoutParams.height = cameraResolution.x;
layoutParams.width = cameraResolution.y;
好吧,事情做完,希望能帮助你。
Answer 9:
我的要求是相机预览必须是全屏,并保持纵横比。 Hesam和尤苏夫的解决方案是伟大的,但我确实看到了高变焦问题的某些原因。
的思路是一样的,具有在父预览容器中心和增加的宽度或高度依赖于纵横比,直到它可以覆盖整个屏幕。
需要注意的一点是预览尺寸为横向,因为我们设定的显示方向。
camera.setDisplayOrientation(90);
我们将SurfaceView视图添加到容器:
<RelativeLayout
android:id="@+id/camera_preview_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"/>
添加预览它在你的活动中心在父容器。
this.cameraPreview = new CameraPreview(this, camera);
cameraPreviewContainer.removeAllViews();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
cameraPreviewContainer.addView(cameraPreview, 0, params);
里面的CameraPreview类:
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (holder.getSurface() == null) {
// preview surface does not exist
return;
}
stopPreview();
// set preview size and make any resize, rotate or
// reformatting changes here
try {
Camera.Size nativePictureSize = CameraUtils.getNativeCameraPictureSize(camera);
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
parameters.setPictureSize(nativePictureSize.width, nativePictureSize.height);
camera.setParameters(parameters);
camera.setDisplayOrientation(90);
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
if (supportedPreviewSizes != null && optimalSize == null) {
optimalSize = CameraUtils.getOptimalSize(supportedPreviewSizes, width, height);
Log.i(TAG, "optimal size: " + optimalSize.width + "w, " + optimalSize.height + "h");
}
float previewRatio = (float) optimalSize.height / (float) optimalSize.width;
// previewRatio is height/width because camera preview size are in landscape.
float measuredSizeRatio = (float) width / (float) height;
if (previewRatio >= measuredSizeRatio) {
measuredHeight = height;
measuredWidth = (int) ((float)height * previewRatio);
} else {
measuredWidth = width;
measuredHeight = (int) ((float)width / previewRatio);
}
Log.i(TAG, "Preview size: " + width + "w, " + height + "h");
Log.i(TAG, "Preview size calculated: " + measuredWidth + "w, " + measuredHeight + "h");
setMeasuredDimension(measuredWidth, measuredHeight);
}
Answer 10:
您必须设置cameraView.getLayoutParams()。高度和cameraView.getLayoutParams()。根据你想要的宽高比的宽度。
Answer 11:
我放弃了计算,并简单地得到相机预览显示我想要的视图的大小,并在我的自定义SurfaceView执行设置相机的预览大小相同(只是翻宽度/高度,由于旋转):
@Override // CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Display display = ((WindowManager) getContext().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
if (display.getRotation() == Surface.ROTATION_0) {
final Camera.Parameters params = camera.getParameters();
// viewParams is from the view where the preview is displayed
params.setPreviewSize(viewParams.height, viewParams.width);
camera.setDisplayOrientation(90);
requestLayout();
camera.setParameters(params);
}
// I do not enable rotation, so this can otherwise stay as is
}
文章来源: Android Camera Preview Stretched