【发布时间】:2012-10-17 16:07:45
【问题描述】:
Camera.setDisplayOrientation 的documentation page 包含以下代码示例,说明使用它将“使相机图像以与显示器相同的方向显示”:
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。
编辑: Here 是我的相机相关代码,我已经在 Nexus One 和三星 Galaxy S Plus 上对其进行了测试。在my head-tracking 3D app 中使用,预览显示在左下角,并且应该始终具有正确的方向。
解决方案(有点): 看起来代码是正确的,但我的测试手机(三星 Galaxy S Plus)返回的前置摄像头的 CameraInfo.orientation 值不正确。有很多关于在此模型上颠倒显示预览的相关讨论(示例here 和here)。一种解决方法是添加一个手动旋转图像的选项。
【问题讨论】:
-
不幸的是,Android 文档中有很多错误,但它们正在变得更好。我测试了您的代码,并在我的设备上体验到了与您相同的体验。我建议你去这里:code.google.com/p/android/issues/…
标签: android android-camera screen-orientation