4

I'm having an issue with the Camera2 API, I'm basicly working with Google sample code (Camera2Basic), but I do changed the TextureView size so it does not span on the entire screen, the screen also have a ToolBar.

The preview display I'm getting is very skewed.

The TextureView size is    w:1080   h:1620   (2/3)
The preview size is        w:720    h:480    (3/2)

Here's the code for configureTransform

  private void configureTransform(int viewWidth, int viewHeight) {
        if (null == mTextureView || null == mPreviewSize || null == activity) {
            return;
        }

        Log.i(CameraFragment.LOG_TAG, "viewWidth: " + viewWidth + "   viewHeight: " + viewHeight + "   ratio: " + (float)viewWidth/(float)viewHeight);
        Log.i(CameraFragment.LOG_TAG, "previewWidth: " + mPreviewSize.getWidth() + "   previewHeight: " + mPreviewSize.getHeight() + "   ratio: " + (float)mPreviewSize.getWidth()/(float)mPreviewSize.getHeight());
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        Matrix matrix = new Matrix();
        RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
        RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
        float centerX = viewRect.centerX();
        float centerY = viewRect.centerY();
        if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
            bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
            matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
            float scale = Math.max(
                    (float) viewHeight / mPreviewSize.getHeight(),
                    (float) viewWidth / mPreviewSize.getWidth());
            matrix.postScale(scale, scale, centerX, centerY);
            matrix.postRotate(90 * (rotation - 2), centerX, centerY);
        } else if (Surface.ROTATION_180 == rotation) {
            matrix.postRotate(180, centerX, centerY);
        }
        mTextureView.setTransform(matrix);
    }
madhead
  • 31,729
  • 16
  • 153
  • 201
Aviran
  • 5,160
  • 7
  • 44
  • 76
  • You may want to consider using the Jetpack camera library's PreviewView, which takes care of this for you. It's a lot of careful handling of rotations and scaling, and testing it in a wide range of conditions: https://developer.android.com/reference/androidx/camera/viewfinder/CameraViewfinder – Eddy Talvala Aug 23 '23 at 00:55

0 Answers0