Android camera2 api preview orientation

In the android camera2 api preview orientation episode we provide orientation support for the preview screen that affects some none nexus devices.

Get Code

The code is now on github you can get it from here Tag camera2-preview-orientation

or else run this command

git clone –branch camera2-preview-orientation

Code Samples


Implement the transform method that scales & rotates the TextureView to the correct orienation

private void transformImage(int width, int height) {
      if(mPreviewSize == null || mTextureView == null) {
      Matrix matrix = new Matrix();
      int rotation = getWindowManager().getDefaultDisplay().getRotation();
      RectF textureRectF = new RectF(0, 0, width, height);
      RectF previewRectF = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
      float centerX = textureRectF.centerX();
      float centerY = textureRectF.centerY();
      if(rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) {
          previewRectF.offset(centerX - previewRectF.centerX(),
                  centerY - previewRectF.centerY());
          matrix.setRectToRect(textureRectF, previewRectF, Matrix.ScaleToFit.FILL);
          float scale = Math.max((float)width / mPreviewSize.getWidth(),
                  (float)height / mPreviewSize.getHeight());
          matrix.postScale(scale, scale, centerX, centerY);
          matrix.postRotate(90 * (rotation - 2), centerX, centerY);

Call the transform method from onResume() & the SurfaceTextureListener callback

public void onResume() {


     if(mTextureView.isAvailable()) {
         setupCamera(mTextureView.getWidth(), mTextureView.getHeight());
         transformImage(mTextureView.getWidth(), mTextureView.getHeight());
     } else {
private TextureView.SurfaceTextureListener mSurfaceTextureListener =
          new TextureView.SurfaceTextureListener() {
              public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                  setupCamera(width, height);
                  transformImage(width, height);

              public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {


              public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                  return false;

              public void onSurfaceTextureUpdated(SurfaceTexture surface) {

About The Author

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>