Android Camera2 API延伸预览

时间:2017-01-19 22:15:15

标签: java android android-camera2

我正在使用Google示例项目,但似乎无法在不延伸的情况下使预览工作。

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

我尝试在AutoFitTextureView类上实际更改宽高比,这使它全屏显示,但会使其拉伸。

有没有人想出这个的成功实施?

1 个答案:

答案 0 :(得分:1)

您需要修改setUpCameraOutputs方法。修改以下行

<强>先前---&GT;

   Size largest = Collections.max(
                        Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
                        new CompareSizesByArea());

<强>改性---&GT;

largest =getFullScreenPreview(map.getOutputSizes(ImageFormat.JPEG),width,height);

<强>先前---&GT;

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

<强>改性----&GT;

  mPreviewSize = getFullScreenPreview(map.getOutputSizes(SurfaceTexture.class),
                    width, height);

获取全屏预览的方法如下 -

 private Size getFullScreenPreview(Size[] outputSizes, int width, int height) {

        List<Size> outputSizeList = Arrays.asList(outputSizes);
        outputSizeList = sortListInDescendingOrder(outputSizeList); //because in some phones available list is in ascending order
        Size fullScreenSize = outputSizeList.get(0);
        for (int i = 0; i < outputSizeList.size(); i++) {
            int orginalWidth = outputSizeList.get(i).getWidth();
            int orginalHeight = outputSizeList.get(i).getHeight();
            float orginalRatio = (float) orginalWidth / (float) orginalHeight;
            float requiredRatio;
            if (width > height) {
                requiredRatio = ((float) width / height); //for landscape mode
                if ((outputSizeList.get(i).getWidth() > width && outputSizeList.get(i).getHeight() > height)) {
                    // because if we select preview size hire than device display resolution it may fail to create capture request
                    continue;
                }
            } else {
                requiredRatio = 1 / ((float) width / height); //for portrait mode
                if ((outputSizeList.get(i).getWidth() > height && outputSizeList.get(i).getHeight() > width)) {
                    // because if we select preview size hire than device display resolution it may fail to create capture request
                    continue;
                }
            }
            if (orginalRatio == requiredRatio) {
                fullScreenSize = outputSizeList.get(i);
                break;
            }
        }
        return fullScreenSize;
    }