Android Camera2 API preview sometimes distorted

眉间皱痕 提交于 2019-12-01 12:13:44

I am facing the same issue on Sony Xperia Z3 Tablet Compact.

The pull request that Alex pointed out doesn't seem to work for me. It results in camera preview larger than the view's area (preview is cropped).

While I was not able to track the issue specifically, I was able to find a workaround. It seems the distortion happens while there are changes of mTextureView's size while in process of opening camera. Delaying the camera opening procedure fixes the issue.

Modified openCamera method:

/**
 * Opens the camera specified by {@link StepFragmentCamera#mCameraId}.
 */
private void openCamera(int width, int height) {
    startBackgroundThread();

    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
        requestCameraPermission();
        return;
    }
    setUpCameraOutputs(width, height);
    configureTransform(width, height);

    /*
     * Delay the opening of the camera until (hopefully) layout has been fully settled.
     * Otherwise there is a chance the preview will be distorted (tested on Sony Xperia Z3 Tablet Compact).
     */
    mTextureView.post(new Runnable() {
        @Override
        public void run() {
            /*
             * Carry out the camera opening in a background thread so it does not cause lag
             * to any potential running animation.
             */
            mBackgroundHandler.post(new Runnable() {
                @Override
                public void run() {
                    Activity activity = getActivity();
                    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
                    try {
                        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
                            throw new RuntimeException("Time out waiting to lock camera opening.");
                        }
                        manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
                    }
                }
            });
        }
    });
}

The Google Camera2Basic sample was finally fixed. The original code had a tiny < vs > mistake. It had been wrong for 2 years.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!