相机设置显示方向的文档页面包含以下代码示例,说明使用它将“使相机图像在与显示器相同的方向上显示”:
public static void setCameraDisplayOrientation(Activity activity,
int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
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;
}
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);
}
然而,我在使用它时遇到了问题,有时图像会出现倒置的情况。经过一些试错,我发现正确的代码应该是(替换该方法的最后8行):
int result = (360 + info.orientation - degrees) % 360;
camera.setDisplayOrientation(result);
(这意味着用于背面相机的计算方法对前置相机也是正确的。)“补偿镜子”的评论有点奇怪,因为旋转无法撤消镜像,该操作只会交换90°和270°的旋转,这对我来说没有任何意义。
所以问题是:示例确实有误还是我漏了什么? 我在多台设备上尝试过,包括前置和后置摄像头以及所有支持的方向,因此我知道我的代码是有效的。可能值得一提的一个小细节是:所有我的设备都将90°返回为info.orientation
。
编辑:这里是我的与相机相关的代码,我已在Nexus One和三星Galaxy S Plus上测试过。它用于我的头部跟踪3D应用程序,预览显示在左下角,并且应始终具有正确的方向。
解决方案 (有点): 看起来代码是正确的,但我的测试手机 (三星 Galaxy S Plus) 返回了前置摄像头的 CameraInfo.orientation 的错误值。关于此型号预览显示颠倒的相关讨论很多 (例如 这里 和 这里)。修复的方法是包括一个手动旋转图像的选项。