SoFunction
Updated on 2025-03-01

Solution to the problem of rotation of preview screen when calling Camera in Android programming

This article describes the solution to the problem of rotation of the preview screen when calling Camera in Android programming. Share it for your reference, as follows:

When calling Camera to write applications, the situation of front and rear cameras is sometimes different. Sometimes, even though the rear camera is clearly not a problem, but when calling the front camera, it is reversed by 180°, or other angles, and it is hard to figure it out. After checking the Android source code, I found that its solution is very good. Next, I will post a source code for future viewing.

public static int getDisplayRotation(Activity activity) {
  int rotation = ().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  for
  // documentation.
   info = new ();
  (cameraId, info);
  int degrees = getDisplayRotation(activity);
  int result;
  if ( == .CAMERA_FACING_FRONT) {
    result = ( + degrees) % 360;
    result = (360 - result) % 360; // compensate the mirror
  } else { // back-facing
    result = ( - degrees + 360) % 360;
  }
  (result);
}

When calling Camera, just call setCameraDisplayOrientation method.

I hope this article will be helpful to everyone's Android programming design.