首页 > 解决方案 > camera2 捕捉与预览不同的图像

问题描述

我的捕获图片输出与我在横向模式下的相机预览不同

  1. 拍摄前 捕获前

  2. 捕获后

捕获后

怎么了 ?我做了什么。谢谢

标签: androidjpegandroid-camera2

解决方案


这是AutoFitTextView我从 Google 示例中提取的课程。你可以看看这里。它旨在显示相机视图并根据设备的物理尺寸配置比例。

public class AutoFitTextureView extends TextureView {

    private int mRatioWidth = 0;
    private int mRatioHeight = 0;

    // Some codes here...

    public void setAspectRatio(int width, int height) {
        if (width < 0 || height < 0) {
            throw new IllegalArgumentException("Size cannot be negative.");
        }
        mRatioWidth = width;
        mRatioHeight = height;
        requestLayout();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        if (0 == mRatioWidth || 0 == mRatioHeight) {
            setMeasuredDimension(width, height);
        } else {
            if (width < height * mRatioWidth / mRatioHeight) {
                setMeasuredDimension(width, width * mRatioHeight / mRatioWidth);
            } else {
                setMeasuredDimension(height * mRatioWidth / mRatioHeight, height);
            }
        }
    }
}

本课有2点:

  1. 您无法确保该比率在每个设备中都能正常工作。但是,我们可以选择已在此类中定义的优化大小
  2. 这个条件是错误的: if (width < height * mRatioWidth / mRatioHeight)。应该是>因为当宽度大于高度时,我们根据宽度(而不是高度)计算和设置测量尺寸。

更新

如果您只是希望每个设备都能以特定的比例正常工作,那么为其设置硬比例(例如:4/3)

您可以通过替换这些代码行来实现:

mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
                        rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
                        maxPreviewHeight, largest);

-> previewSize = Size(4, 3)

推荐阅读