在横向模式下旋转cameraX预览

时间:2020-02-26 02:16:57

标签: java android-studio android-camerax

我正在使用CameraX预览和捕获图像。预览在纵向模式下工作正常,但在横向模式下则不会旋转并显示拉伸的图像。如何确保预览在横向上看起来不错?目前,我在updateTransform中检查屏幕的方向。我尝试记录旋转,但纵向和横向始终为0度。我尝试手动设置旋转角度,但是旋转时预览不显示任何内容。

这是我的updateTransform代码

private void updateTransform(){
        Matrix mx = new Matrix();
        float w = textureView.getMeasuredWidth();
        float h = textureView.getMeasuredHeight();

        float cX = w / 2f;
        float cY = h / 2f;

        int rotation = (int)textureView.getRotation();

        if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){

            Log.i("Orientation", "POrtrait");
        }
        else if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){

            Log.i("Orientation", "Landscape");
        }

        int rotationDgr;

        Log.i("Orientation", "Rotation is " + rotation);

        switch(rotation){
            case Surface.ROTATION_0:
                rotationDgr = 0;
                break;
            case Surface.ROTATION_90:
                rotationDgr = 90;
                break;
            case Surface.ROTATION_180:
                rotationDgr = 180;
                break;
            case Surface.ROTATION_270:
                rotationDgr = 270;
                break;
            default:
                return;
        }

        mx.postRotate(-rotationDgr, cX, cY);
        textureView.setTransform(mx);
    }

和我的相机

CameraX.unbindAll();


        //CameraControl cameraControl = CameraX.getCameraControl(CameraX.LensFacing.BACK);

        Rational aspectRatio = new Rational (textureView.getWidth(), textureView.getHeight());
        Size screen = new Size(textureView.getWidth(), textureView.getHeight()); //size of the screen

        PreviewConfig pConfig = new PreviewConfig.Builder().setTargetAspectRatio(aspectRatio).setTargetResolution(screen).setTargetRotation(Surface.ROTATION_0).build();
        preview = new Preview(pConfig);

        preview.setOnPreviewOutputUpdateListener(
                new Preview.OnPreviewOutputUpdateListener() {
                    //to update the surface texture we  have to destroy it first then re-add it
                    @Override
                    public void onUpdated(Preview.PreviewOutput output){
                        ViewGroup parent = (ViewGroup) textureView.getParent();
                        parent.removeView(textureView);
                        parent.addView(textureView, 0);

                        textureView.setSurfaceTexture(output.getSurfaceTexture());
                        updateTransform();
                    }
                });

0 个答案:

没有答案