安卓(Android) 怎么获取相机(Camera)的显示方向

2019年10月27日22:29:46安卓(Android) 怎么获取相机(Camera)的显示方向已关闭评论 303 1359字阅读4分31秒

1.简介

安卓(Android) 怎么获取相机(Camera)的显示方向?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */



import android.content.Context;
import android.hardware.Camera;

import android.view.Surface;

import android.view.WindowManager;

public class Main {
    public static int getDisplayOrientationForCamera(Context context,
            int cameraId) {
        final int DEGREES_IN_CIRCLE = 360;
        int temp = 0;
        int previewOrientation = 0;

        try {
            Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
            Camera.getCameraInfo(cameraId, cameraInfo);

            int deviceOrientation = getDeviceOrientationDegrees(context);
            switch (cameraInfo.facing) {
            case Camera.CameraInfo.CAMERA_FACING_BACK:
                temp = cameraInfo.orientation - deviceOrientation
                        + DEGREES_IN_CIRCLE;
                previewOrientation = temp % DEGREES_IN_CIRCLE;
                break;
            case Camera.CameraInfo.CAMERA_FACING_FRONT:
                temp = cameraInfo.orientation + deviceOrientation
                        % DEGREES_IN_CIRCLE;
                previewOrientation = (DEGREES_IN_CIRCLE - temp)
                        % DEGREES_IN_CIRCLE;
                break;
            }
        } catch (Exception e) {
            
        }

        return previewOrientation;
    }

    public static int getDeviceOrientationDegrees(Context context) {
        int degrees = 0;

        try {
            WindowManager windowManager = (WindowManager) context
                    .getSystemService(Context.WINDOW_SERVICE);
            int rotation = windowManager.getDefaultDisplay().getRotation();

            switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
            }
        } catch (Exception e) {
            
        }

        return degrees;
    }
}

 
继续阅读
编程十万个怎么办