当前位置: 首页 > 知识库问答 >
问题:

即使在设置了正确的尺寸后,相机预览仍会拉伸

常自怡
2023-03-14

我正在创建一个相机应用程序,实现它自己的相机预览拍照。该应用目前强制进入人像模式。

我的问题是来自相机的预览略有拉伸(纵横比有点偏)。有趣的是,我正在设置我的SurfaceView大小总是匹配预览大小。这确保纵横比应始终保持...但它不是...

下面是我用来展示相机预览的布局:

public class Cp extends ViewGroup implements SurfaceHolder.Callback {
    private final String TAG = "CameraPreview";

    private boolean mPreviewRunning = false;

    private SurfaceView mSurfaceView;
    private SurfaceHolder mHolder;
    private Size mPreviewSize;
    private List<Size> mSupportedPreviewSizes;
    private Camera mCamera;

    public boolean IsPreviewRunning() {
        return mPreviewRunning;
    }

    public Cp(Context context) {
        this(context, null, 0);
    }

    public Cp(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public Cp(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        mSurfaceView = new SurfaceView(context);
        addView(mSurfaceView);

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = mSurfaceView.getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void setCamera(Camera camera) {
        mCamera = camera;
        if (mCamera != null) {
            requestLayout();
        }
    }

    public void switchCamera(Camera camera) {
        setCamera(camera);
        try {
            camera.setPreviewDisplay(mHolder);
        } catch (IOException exception) {
            Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
        }
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
        requestLayout();

        camera.setParameters(parameters);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // We purposely disregard child measurements because act as a wrapper to
        // a SurfaceView that
        // centers the camera preview instead of stretching it.
        final int width = resolveSize(getSuggestedMinimumWidth(),
                widthMeasureSpec);
        final int height = resolveSize(getSuggestedMinimumHeight(),
                heightMeasureSpec);
        setMeasuredDimension(width, height);

        if (mSupportedPreviewSizes == null && mCamera != null) {
            mSupportedPreviewSizes = mCamera.getParameters()
                    .getSupportedPreviewSizes();
        }
        if (mSupportedPreviewSizes != null) {
            mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width,
                    height);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed && getChildCount() > 0) {
            final View child = getChildAt(0);

            final int width = r - l;
            final int height = b - t;

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

            // Center the child SurfaceView within the parent.
            if (width * previewHeight > height * previewWidth) {
                final int scaledChildWidth = previewWidth * height
                        / previewHeight;
                child.layout((width - scaledChildWidth) / 2, 0,
                        (width + scaledChildWidth) / 2, height);
            } else {
                final int scaledChildHeight = previewHeight * width
                        / previewWidth;
                child.layout(0, (height - scaledChildHeight) / 2, width,
                        (height + scaledChildHeight) / 2);
            }
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, acquire the camera and tell it where to
        // draw.
        try {
            if (mCamera != null) {
                Parameters params = mCamera.getParameters();
                mSupportedPreviewSizes = params.getSupportedPreviewSizes();
                mCamera.setPreviewDisplay(holder);
            }
        } catch (IOException exception) {
            Log.e(TAG, "IOException caused by setPreviewDisplay()", exception);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // Surface will be destroyed when we return, so stop the preview.
        stop();
    }

    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;
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

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

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        if (mCamera != null) {
            // Now that the size is known, set up the camera parameters and
            // begin the preview.
            Camera.Parameters parameters = mCamera.getParameters();
            if (mPreviewSize != null) {
                parameters.setPreviewSize(mPreviewSize.width,
                        mPreviewSize.height);
            }
            requestLayout();

            mCamera.setParameters(parameters);
            mCamera.startPreview();
            mPreviewRunning = true;
        }
    }

    public void stop() {
        if (mCamera != null) {
            mCamera.stopPreview();
            mPreviewRunning = false;
            mCamera = null;
        }
    }
}

共有1个答案

汤洋
2023-03-14

我也遇到了同样的问题,在这个谜题中呆了几天之后,我的Java类最终变成了下面的代码:

所以,出现问题是因为相机显示器的大小(高x宽)是576x720,而我的显示器是1184x720。所以,相机预览(我的surface view类)拉伸到填充父级。

所以,我的方法是让这个视图比我的屏幕大,只显示我屏幕的区域。所以,我不得不使用这个奇怪的帧组合(linearlayout中的相对布局),这样相对的大小就可以像我想要的那样大--表面视图将填充其中--而线性将只占我想要显示的部分。

package com.example.frame.camera;

import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.frame.MainActivity;

public class NativeCamera extends SurfaceView implements SurfaceHolder.Callback {

    static private NativeCamera instance;

    private LinearLayout        frame               = null;
    private RelativeLayout      innerFrame          = null;

    private Camera              camera;
    private final SurfaceHolder previewHolder;
    private static final String TAG                 = "NativeCamera.java";

    private boolean             inPreview           = false;
    private boolean             cameraConfigured    = false;
    private boolean             frontCamera         = false;

    private Camera.Size         size;

    static public NativeCamera getInstance() {
        if (NativeCamera.instance == null) {
            if (MainActivity.debug) {
                Log.d(TAG, "Creating Camera Singleton");
            }
            NativeCamera.instance = new NativeCamera(MainActivity.instance);
        }
        return NativeCamera.instance;
    }

    public void onResume() {
        if (MainActivity.debug) {
            Log.d(TAG, "onResume");
        }
        camera = Camera.open();
        if (size != null) {
            initPreview(size.width, size.height);
        }
        startPreview();
    }

    public void onPause() {
        if (MainActivity.debug) {
            Log.d(TAG, "onPause");
        }
        if (inPreview) {
            camera.stopPreview();
        }
        camera.release();
        camera = null;
        inPreview = false;
    }

    public void onDestroy() {
        if (MainActivity.debug) {
            Log.d(TAG, "onDestroy");
        }
        NativeCamera.instance = null;
    }

    public void onSwitch() {
        frontCamera = !frontCamera;
        if (inPreview) {
            camera.stopPreview();
        }
        camera.release();

        int cam = frontCamera ? 1 : 0;

        camera = Camera.open(cam);
        if (size != null) {
            initPreview(size.width, size.height);
        }
        startPreview();
    }

    private NativeCamera(Context context) {
        super(context);
        // TODO Auto-generated constructor stub

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        previewHolder = getHolder();
        previewHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        // previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        innerFrame = new RelativeLayout(MainActivity.instance);
        innerFrame.addView(this);
        frame = new LinearLayout(MainActivity.instance);
        frame.addView(innerFrame);
    }

    public LinearLayout getFrame() {
        return frame;
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        // TODO Auto-generated method stub
        if (MainActivity.debug) {
            Log.d(TAG, "surfaceChanged");
        }
        initPreview(width, height);
        startPreview();
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        // no-op -- wait until surfaceChanged()

    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        // no-op
    }

    private Camera.Size getBestPreviewSize(int width, int height,
            Camera.Parameters parameters) {
        Camera.Size result = null;

        for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
            if (size.width <= width && size.height <= height) {
                if (result == null) {
                    result = size;
                } else {
                    int resultArea = result.width * result.height;
                    int newArea = size.width * size.height;

                    if (newArea > resultArea) {
                        result = size;
                    }
                }
            }
        }

        this.size = result;
        return (result);
    }

    private void initPreview(int width, int height) {
        if (camera != null && previewHolder.getSurface() != null) {

            if (!cameraConfigured) {
                Camera.Parameters parameters = camera.getParameters();
                Camera.Size size = getBestPreviewSize(width, height, parameters);

                if (size != null) {
                    parameters.setPreviewSize(size.width, size.height);
                    camera.setParameters(parameters);
                    cameraConfigured = true;
                    // Setting up correctly the view
                    double ratio = size.height / (double) size.width;
                    LayoutParams params = innerFrame.getLayoutParams();
                    params.height = MainActivity.size.y;
                    params.width = (int) (MainActivity.size.y * ratio);
                    innerFrame.setLayoutParams(params);
                    int deslocationX = (int) (params.width / 2.0 - MainActivity.size.x / 2.0);
                    innerFrame.animate().translationX(-deslocationX);
                }
            }

            try {
                camera.setPreviewDisplay(previewHolder);
                camera.setDisplayOrientation(90);

            } catch (Throwable t) {
                Log.e(TAG, "Exception in setPreviewDisplay()", t);
                Toast.makeText(MainActivity.instance, t.getMessage(), Toast.LENGTH_LONG).show();
            }

        }
    }

    private void startPreview() {
        if (MainActivity.debug) {
            Log.d(TAG, "startPreview");
        }
        if (cameraConfigured && camera != null) {
            camera.startPreview();
            inPreview = true;
        }
    }

}
 类似资料:
  • 对于我在Java中创建的GUI应用程序,我有以下内容: 一个JFrame,设置为最小大小为(300,200) 一个JSplitPane,其中包含: 在左侧,最小大小为(100,0)的JScrollPane(包含JTree)(我只想将宽度限制为200) 在右边,一个最小大小为(200,0)的JPanel 在以下情况下,尺寸不会给我带来任何问题: 向左调整JSplitPane的大小(到JScrollP

  • 我一直在努力在Android上制作我的自定义相机活动,但当旋转相机时,表面视图的纵横比会变得混乱。 在我的oncreate for the activity中,我设置了framelayout,它保存了显示相机参数的曲面视图。 然后,在曲面视图中,我设置要显示的相机参数 您可以看到,当手机旋转时,乐高男会变得更高、更瘦: 如何确保相机视图的纵横比正确?

  • 我有一个SurfaceView可以在我的Android应用程序中显示一个实时相机预览图像。SurfaceView覆盖了纵向屏幕的整个宽度和屏幕高度的一部分。 我试着设置了各种预览尺寸,所以预览有一个扭曲的纵横比,矮胖或者高高的骨瘦如柴。 我打印了显示实际预览显示大小和可用预览相机大小的调试,这样我就可以计算出纵横比错误。 我试穿了这个 阿尔卡特995,Android 4.0.4 三星Note 2,

  • 我已经和https://github.com/commonsguy/cwac-camera 创建了我的自定义CameraFragment和自定义CameraHost。 我已经重写了getPictureSize和getPreviewSize。通过这两种方法,我能够找出可以使用的大小。我的总体想法是拍摄一幅方形图像,并在拍摄前预览它。 我一直在测试,没有设备返回正方形格式的大小,所以我想最好的方法是选

  • 我在玩谷歌的API2摄像头,我的代码有一些问题。我有两个不同的摄像头,一个用于视频,另一个用于图像。为了提高效率,我将代码更改为使用唯一会话,并使应用程序更高效。 在我这样做之后,我的相机预览不能充分工作。当我使用4:3宽高比时,我的预览会在高处拉伸。换句话说,当我使用16:9的比例时,它看起来很好。在这两种情况下,我的照片看起来都很好,我的意思是,预览不能正确工作,但是我拍的照片有正确的宽高比。

  • 我正在创建带有摄像头功能的Android应用程序。相机屏幕包含顶部的工具栏、工具栏下方的surfaceview(相机预览)以及屏幕底部的相机控制按钮。屏幕总是纵向的。 [删除与问题无关的部分代码行] 这是我的片段 这是预览