android相机预览错误的宽高比

时间:2013-07-23 07:46:58

标签: android android-camera

我根据教程创建了一个相机应用程序。我使用的预览类来自api-Demos“CameraPreview”。我添加了here的修改(预览总是旋转90°)。这就是我设置预览尺寸的方式:

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    // Now that the size is known, set up the camera parameters and begin
    // the preview.
    Camera.Parameters parameters = mCamera.getParameters();
    Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

    if (display.getRotation() == Surface.ROTATION_0) {
        parameters.setPreviewSize(mPreviewSize.height, mPreviewSize.width);
        mCamera.setDisplayOrientation(90);
    }

    if (display.getRotation() == Surface.ROTATION_90) {
        parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
    }

    if (display.getRotation() == Surface.ROTATION_180) {
        parameters.setPreviewSize(mPreviewSize.height, mPreviewSize.width);
    }

    if (display.getRotation() == Surface.ROTATION_270) {
        parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
        mCamera.setDisplayOrientation(180);
    }
    parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);

    requestLayout();

    mCamera.setParameters(parameters);
    mCamera.startPreview();
}

但预览显示的宽高比错误。是因为上面的代码还是因为我使用的布局?:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<Button
    android:id="@+id/button_capture"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true" 
    android:text="@string/capture" />

<FrameLayout
    android:id="@+id/camera_preview"
    android:layout_width="100dp"
    android:layout_height="match_parent"/>

那么如何获得正确的宽高比?提前谢谢。

P.S。我从以下网址阅读答案:Android camera preview look strange 但这不适合我。

5 个答案:

答案 0 :(得分:22)

尝试添加此功能来更改预览尺寸:

private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
    final double ASPECT_TOLERANCE = 0.05;
    double targetRatio = (double) w/h;

    if (sizes==null) return null;

    Camera.Size optimalSize = null;

    double minDiff = Double.MAX_VALUE;

    int targetHeight = h;

    // Find size
    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;
}

并根据这些优化值设置尺寸:

List<Camera.Size> sizes = parameters.getSupportedPreviewSizes();
Camera.Size optimalSize = getOptimalPreviewSize(sizes, getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels);

parameters.setPreviewSize(optimalSize.width, optimalSize.height);

我希望这有效:)

祝你好运

Henric

答案 1 :(得分:5)

以下代码修改相机预览容器的宽度/高度以匹配相机预览的宽高比。

    Camera.Size size = camera.getParameters().getPreviewSize();

    //landscape
    float ratio = (float)size.width/size.height;

    //portrait
    //float ratio = (float)size.height/size.width;

    preview = (FrameLayout) findViewById(R.id.camera_preview);

    int new_width=0, new_height=0;
    if(preview.getWidth()/preview.getHeight()<ratio){
        new_width = Math.round(preview.getHeight()*ratio);
        new_height = cameraPreview.getHeight();
    }else{
        new_width = preview.getWidth();
        new_height = Math.round(preview.getWidth()/ratio);
    }
    preview.setLayoutParams(new FrameLayout.LayoutParams(new_width, new_height));

答案 2 :(得分:2)

使用上面的解决方案,使用private size getOptimalPreviewSize方法(List sizes,int w,int h)。 工作得很好!我在纵向方向上遇到纵横比问题:这是我使用的解决方案。将它与android的文档混合:

  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.

            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
            Camera.Parameters params = mCamera.getParameters();
            params.set("orientation", "portrait");
            Size optimalSize=getOptimalPreviewSize(params.getSupportedPreviewSizes(),  getResources().getDisplayMetrics().widthPixels, getResources().getDisplayMetrics().heightPixels);
            params.setPreviewSize(optimalSize.width, optimalSize.height);
            mCamera.setParameters(params);
            // start preview with new settings
            try {

                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();

            } catch (Exception e){
                Log.d(TAG, "Error starting camera preview: " + e.getMessage());
            }
        }
    }

答案 3 :(得分:2)

问题实际上是你布局的方式。 onLayout课程中有覆盖Preview。其工作的想法是根据找到的最佳SurfaceView设置子Size大小。但它不考虑轮换,所以你需要自己做:

  if (mPreviewSize != null) {
    previewWidth = mPreviewSize.height;
    previewHeight = mPreviewSize.width;
  }

而不是

  if (mPreviewSize != null) {
    previewWidth = mPreviewSize.width;
    previewHeight = mPreviewSize.height;
  }

Trick是交换宽度和高度,这是因为

实现了90度旋转
  mCamera.setDisplayOrientation(90);

您可能还会考虑根据您在

中设置的方向分叉子预览尺寸设置
  public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
      //...
  }

(由我提供的代码始终为90度旋转,对于180你不需要做任何旋转,当你没有设置任何旋转时,不需要交换宽度和高度)

另一件值得一提的事情 - 在计算getOptimalPreviewSize的情况下,如果你有旋转并交换子宽度和高度,你也应该传递Preview中交换的父(onMeasure)宽度和高度:

if (mSupportedPreviewSizes != null) {
  //noinspection SuspiciousNameCombination
  final int previewWidth = height;
  //noinspection SuspiciousNameCombination
  final int previewHeight = width;
  mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, previewWidth, previewHeight);
}

答案 4 :(得分:1)

Henric的回答对我不起作用,所以我创建了另一种方法,根据目标视图当前宽度和高度以及活动方向确定任何相机的最佳预览尺寸:

public static Size getOptimalPreviewSize(List<Camera.Size> cameraPreviewSizes, int targetWidth, int targetHeight, boolean isActivityPortrait) {
    if (CommonUtils.isEmpty(cameraPreviewSizes)) {
        return null;
    }

    int optimalHeight = Integer.MIN_VALUE;
    int optimalWidth = Integer.MIN_VALUE;

    for (Camera.Size cameraPreviewSize : cameraPreviewSizes) {
        boolean isCameraPreviewHeightBigger = cameraPreviewSize.height > cameraPreviewSize.width;
        int actualCameraWidth = cameraPreviewSize.width;
        int actualCameraHeight = cameraPreviewSize.height;

        if (isActivityPortrait) {
            if (!isCameraPreviewHeightBigger) {
                int temp = cameraPreviewSize.width;
                actualCameraWidth = cameraPreviewSize.height;
                actualCameraHeight = temp;
            }
        } else {
            if (isCameraPreviewHeightBigger) {
                int temp = cameraPreviewSize.width;
                actualCameraWidth = cameraPreviewSize.height;
                actualCameraHeight = temp;
            }
        }

        if (actualCameraWidth > targetWidth || actualCameraHeight > targetHeight) {
            // finds only smaller preview sizes than target size
            continue;
        }

        if (actualCameraWidth > optimalWidth && actualCameraHeight > optimalHeight) {
            // finds only better sizes
            optimalWidth = actualCameraWidth;
            optimalHeight = actualCameraHeight;
        }
    }

    Size optimalSize = null;

    if (optimalHeight != Integer.MIN_VALUE && optimalWidth != Integer.MIN_VALUE) {
        optimalSize = new Size(optimalWidth, optimalHeight);
    }

    return optimalSize;
}

这使用自定义的Size对象,因为Android的Size在API 21之后可用。

public class Size {

    private int width;
    private int height;

    public Size(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public int getHeight() {
        return height;
    }

    public int getWidth() {
        return width;
    }

}

您可以通过侦听视图的全局布局更改来确定视图的宽度和高度,然后可以设置新的尺寸。这还显示了如何以编程方式确定活动方向:

cameraPreviewLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // gets called after layout has been done but before display.
                cameraPreviewLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);

                boolean isActivityPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
                Size optimalCameraPreviewSize = CustomUtils.getOptimalPreviewSize(cameraPreview.getCameraSizes(), cameraPreviewLayout.getWidth(), cameraPreviewLayout.getHeight(), isActivityPortrait);
                if (optimalCameraPreviewSize != null) {
                    LinearLayout.LayoutParams cameraPreviewLayoutParams = new LinearLayout.LayoutParams(optimalCameraPreviewSize.getWidth(), optimalCameraPreviewSize.getHeight());
                    cameraPreviewLayout.setLayoutParams(cameraPreviewLayoutParams);
                }
            }
        });