Preview size for barcode scanner from vision api

2019-04-20 23:58发布

I'm using the barcode-reader example from Google's Android Vision API. The preview size doesn't seem to fill up the whole space available (I'm using a Nexus 4 and there is a white unused space to the right of preview, about 1/3 of the width).

I would like to be able to run this example on various devices and always have it fill up the whole space available.

So the bit I've been playing with is:

CameraSource.Builder builder = new CameraSource.Builder(getApplicationContext(), barcodeDetector).setFacing(CameraSource.CAMERA_FACING_BACK).setRequestedPreviewSize(?, ?).setRequestedFps(15.0f);

Any ideas?

Thanks!

3条回答
别忘想泡老子
2楼-- · 2019-04-21 00:09

just remove or comment below code from CameraSourcePreview class

if (childHeight > layoutHeight) {
    childHeight = layoutHeight;
    childWidth = (int)(((float) layoutHeight / (float) height) * width);
}

and use layoutHeight instead of childHeight of "CameraSourcePreview" class in this loop - for (int i = 0; i < getChildCount(); ++i){...}

if (mCameraSource != null)
    {
        Size size = mCameraSource.getPreviewSize();
        if (size != null)
        {
            width = size.getWidth();
            height = size.getHeight();
        }
    }

    // Swap width and height sizes when in portrait, since it will be rotated 90 degrees
    if (isPortraitMode())
    {
        int tmp = width;

        //noinspection SuspiciousNameCombination
        width = height;
        height = tmp;
    }

    final int layoutWidth = right - left;
    final int layoutHeight = bottom - top;

    // Computes height and width for potentially doing fit width.
    int childWidth = layoutWidth;
    int childHeight = (int) (((float) layoutWidth / (float) width) * height);

    for (int i = 0; i < getChildCount(); ++i)
    {
        getChildAt(i).layout(0, 0, childWidth, layoutHeight);
    }

    try
    {
        startIfReady();
    }
    catch (SecurityException se)
    {
        Log.e(TAG, "Do not have permission to start the camera", se);
    }
    catch (IOException e)
    {
        Log.e(TAG, "Could not start camera source.", e);
    }
}
查看更多
狗以群分
3楼-- · 2019-04-21 00:10
兄弟一词,经得起流年.
4楼-- · 2019-04-21 00:32

There are two ways to make the camera image fill the entire screen.

  1. Akesh Dubey's answer, which displays the whole image by stretching it to fit the layout's width and height. However, aspect ratio is not preserved.
  2. My answer below, which crops the image to make it fit without sacrificing aspect ratio.

In order to crop-fit the image, all you have to do is change one > into a <. Find the below if-statement and change the condition like so:

if (childHeight < layoutHeight) {
    childHeight = layoutHeight;
    childWidth = (int)(((float) layoutHeight / (float) height) * width);
}
查看更多
登录 后发表回答