Search code examples
androidandroid-camerax

cameraX TextureView preview height is stretched in real device


I'm trying to unstrech the height of the preview that cameraX TextureView is showing.

PreviewConfig previewConfig = new PreviewConfig.Builder()
                .setTargetRotation(getWindowManager().getDefaultDisplay().getRotation())
                .setTargetResolution(new Size(1280, 720))
                .build();

        Preview preview = new Preview(previewConfig);
 <TextureView
        android:id="@+id/view_finder"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

my configuration was very simple as given above.

Whatever resolution i set it's not working at all in any way.

Can anyone tell me how to fix this

look at this image How bottle got shrink. enter image description here

But i'm getting the output was proper. Only preview was like this


Solution

  • you can refer here for more customization https://github.com/android/camera-samples/blob/master/CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/fragments/CameraFragment.kt

    just copy paste these things step by step

    declare two constants

    private double RATIO_4_3_VALUE = 4.0 / 3.0;
    private double RATIO_16_9_VALUE = 16.0 / 9.0;
    

    create a method to choose aspect ratio based on mobile device

    public AspectRatio aspectRatio(int width, int height) {
    
            double previewRatio = Double.valueOf(Math.max(width, height)) / Math.min(width, height);
            if (Math.abs(previewRatio - RATIO_4_3_VALUE) <= Math.abs(previewRatio - RATIO_16_9_VALUE)) {
                return AspectRatio.RATIO_4_3;
            }
            return AspectRatio.RATIO_16_9;
        }
    

    inside startCamera method put this exactly in same way

    private void startCamera() {
    
            WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
            final DisplayMetrics displayMetrics = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(displayMetrics);
            int height = displayMetrics.heightPixels;
            int width = displayMetrics.widthPixels;
    
    
            AspectRatio screenAspectRatio = aspectRatio(width, height);
            PreviewConfig previewConfig = new PreviewConfig.Builder()
                    .setTargetRotation(getWindowManager().getDefaultDisplay().getRotation())
                    .setTargetAspectRatio(screenAspectRatio)
                    .build();
    
    
            Preview preview = new Preview(previewConfig);
    

    This will work 100%