title: Android Camera2 API preview sometimes distorted
body: <p>I am building a custom camera with the Camera2 API.
  So far the camera works very well except for the preview which is distorted sometimes. Let's say I open the camera 7 times in a row. All of the attempts are succesful and the 8th time the camera preview is distorted. It looks like it uses the width as the height and vice versa.</p>
  
  <p>I have based my code on the Google sample implementation of the camera2 which can be found <a href="https://github.com/googlesamples/android-Camera2Basic" rel="nofollow noreferrer">here</a>.
  the interesting thing is that even the Google sample implementation has this distorted preview sometimes. I have tried to modify the AutoFitTextureView but nothing was successful. I am currently using the AutoFitTextureView.java Google provides again.</p>
  
  <p>A similar post to this one <a href="https://stackoverflow.com/questions/30049293/camera-preview-stretched-on-few-android-devices">can be found here</a>.
  However the proposed fixes didn't solve the problem.</p>
  
  <p>I can reproduce the problem by changing the following in the setUpCameraOutputs method:</p>
  
  <pre><code>mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
  </code></pre>
  
  <p>to:</p>
  
  <pre><code>mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
  </code></pre>
  
  <p>Another weird thing is that whenever the distorted preview occurs and you just press the home button so the app goes in onPause() and open up the app again so onResume() gets called, the preview is perfect every time.</p>
  
  <p>Has anyone here experienced this problem and found a fix for it?</p>
  
  <p>Thanks in advance</p>