2017-04-17 625 views
1

我正在使用Android的Camera2 API應用一些應用程序。到目前爲止,我已經能夠在TextureView內顯示預覽。該應用默認處於橫向模式。使用模擬器時,預覽會顛倒顯示。在我的實體Nexus 5上,預覽是,通常正確顯示(風景,不是顛倒),但偶爾它會旋轉90度,但拉伸到屏幕的尺寸。 我認爲應該很容易,以爲下面的代碼將返回在當前方向的必要信息:Android Camera2預覽偶爾旋轉90度

// display rotation 
getActivity().getWindowManager().getDefaultDisplay().getRotation(); 
// sensor orientation 
mManager.getCameraCharacteristics(mCameraId).get(CameraCharacteristics.SENSOR_ORIENTATION); 

...我很驚訝,當我看到上面的代碼總是用於顯示返回1旋轉和90爲傳感器方向,不管預覽旋轉90度或不。 (在仿真器中,傳感器方向始終爲270,如果我假設90是正確的方向,那麼這種方式有意義)。 我還檢查了onMeasure內的AutoMeasureTextureView(採用Android's Camera2 example)中的寬度和高度,我用它來創建我的TextureView。但是沒有任何運氣 - 無論預覽旋轉如何,在onMeasure內報告的寬度和高度總是相同。 所以我對如何解決這個問題一無所知。有沒有人有一個想法是什麼可能是我的預覽方向偶爾hickups的原因?

[編輯] 我剛剛發現的一個細節:每當預覽出現旋轉onSurfaceTextureSizeChangedTextureView.SurfaceTextureListener似乎不會被調用。在onSurfaceTextureSizeChanged的文檔中說,只要SurfaceTexture的緩衝區大小發生改變,就會調用此方法。我有一個方法createCameraPreviewSession(從Android的Camera2例如複製),其中設置我的紋理的默認緩衝區大小像

texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); 

從我的日誌輸出我可以告訴大家,onSurfaceTextureSizeChanged只調用之後 - 但是,沒有永遠...(或者設置默認緩衝區大小有時默默失敗?)。

回答

2

我想我可以回答我自己的問題:我在Android's Camera2 example之後創建了我的Camera2片段。但是,我並沒有真正考慮方法configureTransform,因爲與示例代碼相反,我的應用程序無論如何都被強制爲橫向模式。原來這個假設是錯誤的。由於在我的代碼中有configureTransform重新集成,我沒有經歷過更多的打嗝。

0

我也遇到了Nexus設備上的類似問題。下面的代碼正在爲我工​​作。 在打開相機之前調用此功能,並在Resume()上調用。

私人無效transformImage(INT寬度,高度INT) {

if (textureView == null) { 

     return; 
    } else try { 
     { 
      Matrix matrix = new Matrix(); 
      int rotation = getWindowManager().getDefaultDisplay().getRotation(); 
      RectF textureRectF = new RectF(0, 0, width, height); 
      RectF previewRectF = new RectF(0, 0, textureView.getHeight(), textureView.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/width, (float) height/width); 
       matrix.postScale(scale, scale, centerX, centerY); 
       matrix.postRotate(90 * (rotation - 2), centerX, centerY); 
      } 
      textureView.setTransform(matrix); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 
+0

是如何從斯特凡自己的[答案]不同的(https://stackoverflow.com/a/43506843/192373)? –