Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

解決 Android 調用 Camera 時預覽畫面旋轉的問題

編輯:Android 開發實例

本文分享一個在 Android 中調用 Camera 時,預覽畫面出現旋轉問題的解決方案,供大家參考。

在編寫 Camera 相關應用時,前後攝像頭的情況往往並不一樣。有時後攝像頭顯示正常,可一旦切換到前攝像頭,畫面卻會旋轉 180° 或其他角度,讓人百思不得其解。翻看了 Android 源碼後,發現官方的處理方式非常巧妙,這裡把源碼貼出來,以備日後查閱。

 public static int getDisplayRotation(Activity activity) { int rotation = activity.getWindowManager().getDefaultDisplay() .getRotation(); switch (rotation) { case Surface.ROTATION_0: return 0; case Surface.ROTATION_90: return 90; case Surface.ROTATION_180: return 180; case Surface.ROTATION_270: return 270; } return 0; } public static void setCameraDisplayOrientation(Activity activity, int cameraId, Camera camera) { // See android.hardware.Camera.setCameraDisplayOrientation for // documentation. Camera.CameraInfo info = new Camera.CameraInfo(); Camera.getCameraInfo(cameraId, info); int degrees = getDisplayRotation(activity); int result; if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { result = (info.orientation + degrees) % 360; result = (360 - result) % 360; // compensate the mirror } else { // back-facing result = (info.orientation - degrees + 360) % 360; } camera.setDisplayOrientation(result); } 

關鍵點在於:後攝像頭直接用 (info.orientation - degrees + 360) % 360 計算角度即可;而前攝像頭因為存在鏡像效果,需要多做一次 (360 - result) % 360 來補償。只要打開攝像頭後調用一次 setCameraDisplayOrientation 方法,預覽畫面的方向就能與實際拍攝方向保持一致了。

希望本文所述對大家的 Android 程序設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved