title: I can't view the full image when trying to display camera output in full screen
body: <p>I have had this issue for a few days already and I'm not sure how to fix it. I have a code to open the camera and display the output in full screen. but the displied image is not full. a part of it is not there. I added this function and it fixed the image but the display is not in full screen anymore.
  here are the two images before and after adding the function</p>
  <p>Before
  <a href="https://i.stack.imgur.com/XXBdH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XXBdH.jpg" alt="enter image description here" /></a></p>
  <p>After
  <a href="https://i.stack.imgur.com/TJFR8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TJFR8.jpg" alt="enter image description here" /></a></p>
  <p>the function I added</p>
  <pre><code>private void configureTransform(int viewWidth, int viewHeight) {
          if (null == mTextureView || null == mPreviewSize) {
              return;
          }
          int rotation = 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());
          matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
          
          mTextureView.setTransform(matrix);
      }
  </code></pre>
  <p>my Full code for the camera is here</p>
  <pre><code>package com.example.myapplication;
  
  import androidx.annotation.NonNull;
  import androidx.appcompat.app.AppCompatActivity;
  
  import android.animation.ValueAnimator;
  import android.annotation.SuppressLint;
  import android.app.Fragment;
  import android.content.Context;
  import android.content.DialogInterface;
  import android.content.SharedPreferences;
  import android.content.pm.PackageManager;
  import android.content.res.Configuration;
  import android.graphics.Bitmap;
  import android.graphics.ImageFormat;
  import android.graphics.Matrix;
  import android.graphics.Point;
  import android.graphics.Rect;
  import android.graphics.RectF;
  import android.graphics.SurfaceTexture;
  import android.hardware.camera2.CameraAccessException;
  import android.hardware.camera2.CameraCaptureSession;
  import android.hardware.camera2.CameraCharacteristics;
  import android.hardware.camera2.CameraDevice;
  import android.hardware.camera2.CameraManager;
  import android.hardware.camera2.CameraMetadata;
  import android.hardware.camera2.CaptureRequest;
  import android.hardware.camera2.CaptureResult;
  import android.hardware.camera2.TotalCaptureResult;
  import android.hardware.camera2.params.MeteringRectangle;
  import android.hardware.camera2.params.StreamConfigurationMap;
  import android.media.ImageReader;
  import android.os.Bundle;
  import android.os.Handler;
  import android.os.HandlerThread;
  import android.util.DisplayMetrics;
  import android.util.Log;
  import android.util.Size;
  import android.util.SparseIntArray;
  import android.view.Surface;
  import android.view.TextureView;
  import android.view.View;
  import android.widget.Button;
  import android.widget.ImageButton;
  import android.widget.ProgressBar;
  import android.widget.RelativeLayout;
  import android.widget.TextView;
  
  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.Collections;
  import java.util.Comparator;
  import java.util.List;
  import java.util.concurrent.Semaphore;
  import java.util.concurrent.TimeUnit;
  
  import static android.content.ContentValues.TAG;
  import static java.lang.Math.abs;
  import static java.lang.Math.pow;
  
  
  public class camera_ocr extends AppCompatActivity {
  
  
  
      static int CAMERA_FRONT_BACK = 0;
  
      private MeteringRectangle[] mAFRegions = AutoFocusHelperLib.getZeroWeightRegion();
      private MeteringRectangle[] mAERegions = AutoFocusHelperLib.getZeroWeightRegion();
      private Rect mCropRegion;
      private Boolean cameraReady = false;
      private static String versionName = &quot;V7.7.5&quot;;
      private int flag = 0;
      private int[] position;
      private View linearLayout;
      private static final String TAG = &quot;Camera Error&quot;;
      private int[] focusMode = {};
      private CameraCharacteristics cameraChar;
      private Fragment fragment;
      private Bitmap output;
      private static int totalRotation;
      ImageButton camera;
      ImageButton flashLight ;
      Button btnSnapPhoto;
      private static Boolean displayResult = false;
      Boolean cameraGranted = false;
      public static  String licenseKey ;
      ValueAnimator animation = null ;
  
      private int[] boxPosition = new int[4];
      private float [] cardPosation = new float[8];
      private static final int CAMERA_PERMISSION = 123;
      private String mCameraId;
      private Size mPreviewSize;
      private CaptureRequest.Builder mCaptureRequestBuilder;
      private HandlerThread mBackgroundHandlerThread;
      private Handler mBackgroundHandler;
      private static SparseIntArray ORIENTATIONS = new SparseIntArray();
      private float screenWidth ;
      private float screenHeight ;
  
      CameraCharacteristics characteristics;
      private CaptureRequest mPreviewRequest;
      private CameraCaptureSession mCaptureSession;
  
      private int mSensorOrientation;
  
  
      private CaptureRequest.Builder mPreviewRequestBuilder;
      private int mState = STATE_PREVIEW;
  
      private ImageReader mImageReader;
  
  
  
      private float cameraFocusDistance = 4.5f ;
      static {
          ORIENTATIONS.append(Surface.ROTATION_0, 0);
          ORIENTATIONS.append(Surface.ROTATION_90, 90);
          ORIENTATIONS.append(Surface.ROTATION_180, 180);
          ORIENTATIONS.append(Surface.ROTATION_270, 270);
      }
      private static CameraDevice mCameraDevice;
  
      /**
       * Camera state: Showing camera preview.
       */
      private static final int STATE_PREVIEW = 0;
  
      /**
       * Camera state: Waiting for the focus to be locked.
       */
      private static final int STATE_WAITING_LOCK = 1;
  
      /**
       * Camera state: Waiting for the exposure to be precapture state.
       */
      private static final int STATE_WAITING_PRECAPTURE = 2;
  
      /**
       * Camera state: Waiting for the exposure state to be something other than precapture.
       */
      private static final int STATE_WAITING_NON_PRECAPTURE = 3;
  
      /**
       * Camera state: Picture was taken.
       */
      private static final int STATE_PICTURE_TAKEN = 4;
  
      /**
       * Max preview width that is guaranteed by Camera2 API
       */
      private static final int MAX_PREVIEW_WIDTH = 1920;
  
      /**
       * Max preview height that is guaranteed by Camera2 API
       */
      private static final int MAX_PREVIEW_HEIGHT = 1080;
      private Semaphore mCameraOpenCloseLock = new Semaphore(1);
      CameraManager manager = null ;
  
      private AutoFitTextureViewLib mTextureView;
  
      @SuppressLint(&quot;MissingPermission&quot;)
      private void openCamera(int width, int height, int camera_front_back) {
          setUpCameraOutputs(width, height, camera_front_back);
          configureTransform(width, height);
          manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
          try {
              if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
                  throw new RuntimeException(&quot;Time out waiting to lock camera opening.&quot;);
              }
  
              manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
  
  //            getCurrentPhoto();
          } catch (CameraAccessException e) {
              e.printStackTrace();
          } catch (InterruptedException e) {
              throw new RuntimeException(&quot;Interrupted while trying to lock camera opening.&quot;, e);
          }
      }
  
      static class CompareSizesByArea implements Comparator&lt;Size&gt; {
  
          @Override
          public int compare(Size lhs, Size rhs) {
              // We cast here to ensure the multiplications won't overflow
              return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
                      (long) rhs.getWidth() * rhs.getHeight());
          }
      }
  
      private static Size chooseOptimalSize(Size[] choices, int textureViewWidth,
                                            int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio) {
  
          // Collect the supported resolutions that are at least as big as the preview Surface
          List&lt;Size&gt; bigEnough = new ArrayList&lt;&gt;();
          // Collect the supported resolutions that are smaller than the preview Surface
          List&lt;Size&gt; notBigEnough = new ArrayList&lt;&gt;();
          int w = aspectRatio.getWidth();
          int h = aspectRatio.getHeight();
          for (Size option : choices) {
              if (option.getWidth() &lt;= maxWidth &amp;&amp; option.getHeight() &lt;= maxHeight &amp;&amp;
                      option.getHeight() == option.getWidth() * h / w) {
                  if (option.getWidth() &gt;= textureViewWidth &amp;&amp;
                          option.getHeight() &gt;= textureViewHeight) {
                      bigEnough.add(option);
                  } else {
                      notBigEnough.add(option);
                  }
              }
          }
  
          // Pick the smallest of those big enough. If there is no one big enough, pick the
          // largest of those not big enough.
          if (bigEnough.size() &gt; 0) {
              return Collections.min(bigEnough, new CompareSizesByArea());
          } else if (notBigEnough.size() &gt; 0) {
              return Collections.max(notBigEnough, new CompareSizesByArea());
          } else {
              Log.e(TAG, &quot;Couldn't find any suitable preview size&quot;);
              return choices[0];
          }
      }
  
      private void setUpCameraOutputs(int width, int height, int camera_front_back) {
          CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
          try {
              String cameraId = manager.getCameraIdList()[camera_front_back];
              characteristics = manager.getCameraCharacteristics(cameraId);
  
  
              StreamConfigurationMap map = characteristics.get(
                      CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
              if (map == null) {
                  return;
              }
  
              // For still image captures, we use the largest available size.
              Size largest = Collections.max(
                      Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
                      new CompareSizesByArea());
              mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
                      ImageFormat.JPEG, /*maxImages*/2);
  
              // Find out if we need to swap dimension to get the preview size relative to sensor
              // coordinate.
              int displayRotation = getWindowManager().getDefaultDisplay().getRotation();
              //noinspection ConstantConditions
              mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
              boolean swappedDimensions = false;
              switch (displayRotation) {
                  case Surface.ROTATION_0:
                  case Surface.ROTATION_180:
                      if (mSensorOrientation == 90 || mSensorOrientation == 270) {
                          swappedDimensions = true;
                      }
                      break;
                  case Surface.ROTATION_90:
                  case Surface.ROTATION_270:
                      if (mSensorOrientation == 0 || mSensorOrientation == 180) {
                          swappedDimensions = true;
                      }
                      break;
                  default:
                      Log.e(TAG, &quot;Display rotation is invalid: &quot; + displayRotation);
              }
  
              Point displaySize = new Point();
              getWindowManager().getDefaultDisplay().getSize(displaySize);
              int rotatedPreviewWidth = width;
              int rotatedPreviewHeight = height;
              int maxPreviewWidth = displaySize.x;
              int maxPreviewHeight = displaySize.y;
  
              if (swappedDimensions) {
                  rotatedPreviewWidth = height;
                  rotatedPreviewHeight = width;
                  maxPreviewWidth = displaySize.y;
                  maxPreviewHeight = displaySize.x;
              }
  
              if (maxPreviewWidth &gt; MAX_PREVIEW_WIDTH) {
                  maxPreviewWidth = MAX_PREVIEW_WIDTH;
              }
  
              if (maxPreviewHeight &gt; MAX_PREVIEW_HEIGHT) {
                  maxPreviewHeight = MAX_PREVIEW_HEIGHT;
              }
              // Danger, W.R.! Attempting to use too large a preview size could  exceed the camera
              // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
              // garbage capture data.
              mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
                      rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
                      maxPreviewHeight, largest);
  
              // We fit the aspect ratio of TextureView to the size of preview we picked.
              int orientation = getResources().getConfiguration().orientation;
              if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                  mTextureView.setAspectRatio(
                          mPreviewSize.getWidth(), mPreviewSize.getHeight());
              } else {
                  mTextureView.setAspectRatio(
                          mPreviewSize.getHeight(), mPreviewSize.getWidth());
              }
  
  
              mCropRegion = AutoFocusHelperLib.cropRegionForZoom(characteristics,
                      CameraConstantsLib.ZOOM_REGION_DEFAULT);
  
              mCameraId = cameraId;
              return;
          } catch (CameraAccessException e) {
              e.printStackTrace();
          } catch (NullPointerException e) {
              // Currently an NPE is thrown when the Camera2API is used but not supported on the
              // device this code runs.
          }
      }
      private void configureTransform(int viewWidth, int viewHeight) {
          if (null == mTextureView || null == mPreviewSize) {
              return;
          }
          int rotation = 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());
          matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
          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);
      }
  
      private final CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
  
          @Override
          public void onOpened(@NonNull CameraDevice cameraDevice) {
              // This method is called when the camera is opened.  We start camera preview here.
              mCameraOpenCloseLock.release();
              mCameraDevice = cameraDevice;
              createCameraPreviewSession();
          }
  
          @Override
          public void onDisconnected(@NonNull CameraDevice cameraDevice) {
              mCameraOpenCloseLock.release();
              cameraDevice.close();
              mCameraDevice = null;
          }
  
          @Override
          public void onError(@NonNull CameraDevice cameraDevice, int error) {
              mCameraOpenCloseLock.release();
              cameraDevice.close();
              mCameraDevice = null;
              finish();
          }
  
      };
      private void createCameraPreviewSession() {
          try {
              final int[] x = new int[1];
              final int[] y = new int[1];
              SurfaceTexture texture = mTextureView.getSurfaceTexture();
              assert texture != null;
  
              // We configure the size of default buffer to be the size of camera preview we want.
              texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
  
              // This is the output Surface we need to start preview.
              Surface surface = new Surface(texture);
  
              // We set up a CaptureRequest.Builder with the output Surface.
              mPreviewRequestBuilder
                      = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
              mPreviewRequestBuilder.addTarget(surface);
  
              // Here, we create a CameraCaptureSession for camera preview.
              mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                      new CameraCaptureSession.StateCallback() {
  
                          @Override
                          public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                              // The camera is already closed
                              if (null == mCameraDevice) {
                                  return;
                              }
  
                              // GET SCREEN SIZE
                              MeteringRectangle screenSize[] = mPreviewRequestBuilder.get(CaptureRequest.CONTROL_AF_REGIONS);
  
                              // When the session is ready, we start displaying the preview.
                              mCaptureSession = cameraCaptureSession;
  
  
                              long loopTime = System.currentTimeMillis();
                              long time = System.currentTimeMillis();
  
                              // GET SCREEN WIDTH
                              DisplayMetrics displayMetrics = new DisplayMetrics();
                              getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
                              screenWidth = screenSize[0].getWidth();
                              screenHeight = screenSize[0].getHeight();
  
                              // CREATE NEW FOCUS POINT
                              // testing
                              for(int i = 0; i &lt; 1 ; i++) {
                                  setManualFocusAt(x[0], y[0]);
  
                                  // GET CURRENT FOCUS POINT
                                  MeteringRectangle currentFocusArea[] = mPreviewRequestBuilder.get(CaptureRequest.CONTROL_AF_REGIONS);
  
  
                                  time = System.currentTimeMillis();
                                  // WAIT FOR FOCUS TO READY
                                  while((System.currentTimeMillis() - time) &lt; 800){
                                      Log.d(&quot;focus time:&quot; , Float.toString(System.currentTimeMillis() - time));
                                      Log.e(&quot;focus time:&quot; , Float.toString(System.currentTimeMillis() - time));
                                      Log.wtf(&quot;focus time:&quot; , Float.toString(System.currentTimeMillis() - time));
                                  };
                              }
                              long x = System.currentTimeMillis() - loopTime;
                              Log.d(&quot;focus time:&quot; , Float.toString(x));
  
                              cameraReady = true;
  
                          }
  
                          @Override
                          public void onConfigureFailed(
                                  @NonNull CameraCaptureSession cameraCaptureSession) {
                          }
                      }, null
              );
          } catch (CameraAccessException e) {
              e.printStackTrace();
          }
      }
  
      /**
       * Initiate a still image capture.
       */
  
      void setManualFocusAt(int x, int y) {
          int mDisplayOrientation = getWindowManager().getDefaultDisplay().getRotation();
          float points[] = new float[2];
          points[0] = (float) x / mTextureView.getWidth();
          points[1] = (float) y / mTextureView.getHeight();
          Matrix rotationMatrix = new Matrix();
          rotationMatrix.setRotate(mDisplayOrientation, 0.5f, 0.5f);
          rotationMatrix.mapPoints(points);
          if (mPreviewRequestBuilder != null) {
  //            mIsManualFocusing = true;
              updateManualFocus(points[0], points[1]);
              if (mCaptureSession != null) {
                  try {
                      mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                              CaptureRequest.CONTROL_AF_TRIGGER_START);
                      mCaptureSession.capture(mPreviewRequestBuilder.build(), null, mBackgroundHandler);
                      mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER,
                              CaptureRequest.CONTROL_AF_TRIGGER_IDLE);
                      mCaptureSession.setRepeatingRequest(mPreviewRequestBuilder.build(),
                              null, mBackgroundHandler);
                  } catch (CameraAccessException | IllegalStateException e) {
                      Log.e(TAG, &quot;Failed to set manual focus.&quot;, e);
                  }
              }
  //            resumeAutoFocusAfterManualFocus();
          }
      }
  
      void updateManualFocus(float x, float y) {
          @SuppressWarnings(&quot;ConstantConditions&quot;)
          int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
          mAFRegions = AutoFocusHelperLib.afRegionsForNormalizedCoord(x, y, mCropRegion, sensorOrientation);
          mAERegions = AutoFocusHelperLib.aeRegionsForNormalizedCoord(x, y, mCropRegion, sensorOrientation);
          mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_REGIONS, mAFRegions);
          mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_REGIONS, mAERegions);
  //        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_AUTO);
  
          // fixe distance focuse // testing
          mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,CaptureRequest.CONTROL_AF_MODE_OFF);
          mPreviewRequestBuilder.set(CaptureRequest.LENS_FOCUS_DISTANCE, cameraFocusDistance);
  
      }
  
      /**
       * Lock the focus as the first step for a still image capture.
       */
  
      private void closeCamera() {
          try {
              mCameraOpenCloseLock.acquire();
              if (null != mCaptureSession) {
                  mCaptureSession.close();
                  mCaptureSession = null;
              }
              if (null != mCameraDevice) {
                  mCameraDevice.close();
                  mCameraDevice = null;
              }
              if (null != mImageReader) {
                  mImageReader.close();
                  mImageReader = null;
              }
          } catch (InterruptedException e) {
              throw new RuntimeException(&quot;Interrupted while trying to lock camera closing.&quot;, e);
          } finally {
              mCameraOpenCloseLock.release();
          }
      }
  
  
      private final TextureView.SurfaceTextureListener mSurfaceTextureListener
              = new TextureView.SurfaceTextureListener() {
  
          @Override
          public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) {
              openCamera(width, height,CAMERA_FRONT_BACK);
          }
  
          @Override
          public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) {
              configureTransform(width, height);
          }
  
          @Override
          public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
              return true;
          }
  
          @Override
          public void onSurfaceTextureUpdated(SurfaceTexture texture) {
          }
  
      };
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_camera_ocr);
  
          mTextureView = findViewById(R.id.textureView);
  
      }
  
      @Override
      protected void onResume(){
          super.onResume();
  
          if (mTextureView.isAvailable()) {
              openCamera(mTextureView.getWidth(), mTextureView.getHeight(),CAMERA_FRONT_BACK);
          } else {
              mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
          }
      }
  }
  </code></pre>