Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

解決 Android 呼叫 Camera 時預覽畫面旋轉的問題

編輯:關於 Android 程式設計

本文透過實例,講解在 Android 中呼叫 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); } 

使用時,只要在開啟 Camera 之後呼叫 setCameraDisplayOrientation 這個方法,並傳入正確的 cameraId,就能讓預覽畫面自動校正到符合直覺的方向。特別要注意的是,前置鏡頭因為存在鏡像效果,所以需要多做一次角度補償,這也是官方程式碼中特別處理的地方。希望本文所述能對大家的 Android 程式設計有所幫助。

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