欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

解决android 自定义camera变形的问题

程序员文章站 2022-05-08 19:43:19
...

主要是因为surfaceview的显示大小和camera预览Size不匹配导致的。

下面这一段,我也是借鉴别人然后修改传入的surfaceview宽高位置就可以了。

  parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
                List<Camera.Size> sizeList = parameters.getSupportedPreviewSizes();//获取所有支持的camera尺寸
                Log.d("jxd","optionSize : mSurfaceView "+mSurfaceView.getWidth()+" * "+mSurfaceView.getHeight());
                Camera.Size optionSize = getOptimalPreviewSize(sizeList, mSurfaceView.getHeight(), mSurfaceView.getWidth());//获取一个最为适配的camera.size
                Log.d("jxd","optionSize : "+optionSize.width+" * "+optionSize.height);
                parameters.setPreviewSize(optionSize.width,optionSize.height);//把camera.size赋值到parameters
                mCamera.setParameters(parameters);
                //通过SurfaceView显示预览
                mCamera.setPreviewDisplay(mHolder);
                //开始预览
                mCamera.startPreview();

寻找合适的size

 /**
     * 解决预览变形问题
     * @param sizes
     * @param w
     * @param h
     * @return
     */
    private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio = (double) w / h;
        if (sizes == null) return null;

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        // Try to find an size match aspect ratio and 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);
            }
        }

        // Cannot find the one match the aspect ratio, ignore the requirement
        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;
    }

相关标签: camera