Given a screen orientation and a camera (index) - Android android.hardware

Android examples for android.hardware:Camera Orientation

Description

Given a screen orientation and a camera (index)

Demo Code

import android.annotation.TargetApi;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.camera2.CameraCharacteristics;
import android.util.Log;
import android.view.Surface;

public class Main {

  /**/*from  w  w  w .j ava 2  s .c o m*/
   * Given a screen orientation and a camera (index), find the degrees required to
   * rotate the camera to align with the current orientation.
   */
  public static int getRotationDegrees(Activity activity, Camera.CameraInfo info) {
    // The camera's orientation, in ordinal direction degrees
    int cameraOrientation = info.orientation;

    int screenOrientation = activity.getWindowManager().getDefaultDisplay().getRotation();

    // Translate rotation constants into degrees
    if (screenOrientation == Surface.ROTATION_0) {
      screenOrientation = 0;
    } else if (screenOrientation == Surface.ROTATION_90) {
      screenOrientation = 90;
    } else if (screenOrientation == Surface.ROTATION_180) {
      screenOrientation = 180;
    } else {
      screenOrientation = 270;
    }

    // Tare the rotation and get the result in positive degrees. Parens and order of
    // ops are for clarity and to prevent modulo of a negative.
    int degreesToRotate = ((cameraOrientation - screenOrientation) + 360) % 360;

    return degreesToRotate;
  }

  @TargetApi(21)
  public static int getRotationDegrees(Activity activity, CameraCharacteristics characteristics, boolean isFront) {
    // The camera's orientation, in ordinal direction degrees
    int cameraOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);

    int screenOrientation = activity.getWindowManager().getDefaultDisplay().getRotation();

    // Translate rotation constants into degrees
    if (screenOrientation == Surface.ROTATION_0) {
      screenOrientation = 0;
    } else if (screenOrientation == Surface.ROTATION_90) {
      screenOrientation = 90;
    } else if (screenOrientation == Surface.ROTATION_180) {
      screenOrientation = 180;
    } else {
      screenOrientation = 270;
    }

   int degreesToRotate = ((cameraOrientation - screenOrientation) + 360) % 360;

    if (isFront) {
      if (degreesToRotate == 180) {
        degreesToRotate = 0;
      } else if (degreesToRotate == 0) {
        degreesToRotate = 180;
      }
    }

    return degreesToRotate;
  }

}

Related Tutorials