自定义相机的旋转角度适配

Android中时常会需要实现自定义的相机。
但是应用可以横屏竖屏操作,所以自定义相机需要\设置Orientation来保证获得准确的预览效果。
但是这个Orientation应该来如何计算呢?

经过调研发现了Google官方给出的计算方案:

支持5.0之后的手机,虽然5.0之后的相机跟5.0之前内置的旋转角度是不一样的。

<pre><code>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);

}
</code></pre>

保存的图片也要保证有相同的旋转,所以也要通过parameter设置类似的旋转角度。

<pre><code>//orientation表示手机旋转角度,转换成90的整数倍
int rotation;
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
rotation = (cameraInfo.orientation - orientation + 360) % 360;
} else { // back-facing camera
rotation = (cameraInfo.orientation + orientation) % 360;
}
parameters.setRotation(rotation);
</code></pre>

本文中以Camera举例,如果你用的是Camera2 API的话,应该也差不太多.....

附上官方<a href="https://developer.android.com/reference/android/hardware/Camera.html#setDisplayOrientation(int)">链接1</a> <a href="https://developer.android.com/reference/android/hardware/Camera.Parameters.html#setRotation(int)">链接2</a>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,385评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,245评论 4 61
  • ALSNDMGR.CPL AC97 Audio组态设定 appwiz.cpl 添加和删除程序 bthprops.c...
    jianghu000阅读 2,242评论 0 1
  • 要求:请描述反光物品(意思是:比如,光打在镜子上,然后你看到镜子上有光),看到了什么,请写细节,字数不限。 看到题...
    彭玄霏阅读 344评论 0 0