在使用相机时,最自然的效果是不管你的手机如何旋转,手机上的成像始终是向上的,也就是说,相机内容不会随着相机的旋转和旋转。
Camera.Parameters的【setRotation(int)】就是为了实现这个效果的,其中rataion表示相机采集到的图像需要顺时针转动的角度,从而达到成像始终向上。
这个方法的解释中提到了两个角度:【OrientationEventListener】、【Camera.CameraInfo】。
0x01:
根据【OrientationEventListener】的解释:方法中的orientation表示手机从自然角度顺时针旋转的角度。自然角度就是手机正向竖直向上的状态(此时一般前置摄像头在最上面),看看示例图就明白了。

于是乎,手机的几个特定旋转角度和对应的orientation是:




注意,这个接口在传感器检测到有旋转时就会回调,并不只是上述4个状态才会触发,当手机水平放置时,传感器将不能检测到旋转角度,orientation为-1:

这个接口其实挺好理解的。
0x02:
【Camera.CameraInfo】就有点复杂,文档说明了,这个角度是相机图像为了在自然方向上展示时,需要旋转的角度。
相机图像指摄像头最初采集到的图像,相机采集到的图像和相机摄像头摆放的角度有关。上述CameraInfo的文档中讲述了一个例子:假如你的手机现在在自然角度,你手机的后置摄像头的正向此时指向手机的右边框(一般手机就是这种模式,不排除某些厂商瞎搞,把摄像头角度调整成别的),那么这个角度就是90。怎么理解呢,还是来看图:

这样不太舒服,来旋转一下,将后置摄像头正向朝上:

ok,弄明白摄像头的正向位置,再来看相机图像,假如手机处于自然角度,然后拍摄下面这个照片:

拍摄时应该是这个样子:

假如你不做任何处理,你的视野和摄像头是一模一样的,此时摄像头正向的视野应该是:

于是你看到的是:

为了让图像能够在自然方向上展示,你需要顺时针旋转90度。这个角度就是CameraInfo中的orientation值。
0x03:
回到最初,假如我们想要不关心手机的旋转状态,不关心摄像头的安装角度,我们如何获取一个始终是正向的图像呢?
在【setRotation(int)】的说明文档中展示了一段代码:
public void onOrientationChanged(int orientation) {
if (orientation == ORIENTATION_UNKNOWN) return;
android.hardware.Camera.CameraInfo info =
new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
orientation = (orientation + 45) / 90 * 90;
int rotation = 0;
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
rotation = (info.orientation - orientation + 360) % 360;
} else { // back-facing camera
rotation = (info.orientation + orientation) % 360;
}
mParameters.setRotation(rotation);
}
它会根据上述两个角度,计算出相机图像为了正向展示需要旋转的角度,并设置到相机的参数中,至此你就能获取到正向图像了。
为啥是那样的计算公式呢?
以 后置摄像头 为例:
假如手机在自然角度:

此时OrientationEventListener回调中的orientation是0,而摄像头安装角度是固定的90度。根据前面我们的图例,此时看到的图像是向左旋转的,因此我们需要顺时针旋转90度,也就是 (0+90)%360 = 90。
假如手机是摄像头正向朝上:

此时直观上就能发现,相机图像是正向的,不需要做旋转(0度)。此时OrientationEventListener回调中的orientation是270,摄像头安装角度是固定的90度,也就是 (270+90)%360 = 0
ok,我们已经验证了后置摄像头算法的正确性,前置摄像头大家自行去验证。

网友评论