美文网首页
自定义相机的旋转角度适配

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

作者: VictorLiang | 来源:发表于2017-03-19 16:00 被阅读413次

    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>

    相关文章

      网友评论

          本文标题:自定义相机的旋转角度适配

          本文链接:https://www.haomeiwen.com/subject/htamnttx.html