我正在尝试根据屏幕的旋转来调整相机预览的方向。
我注意到,当直接在具有匹配尺寸(因此,0 -> 180 和 90 -> 270)的方向之间旋转时,配置不会更改, Activity 也不会重新启动。
我目前在 Activity.onCreate()
中使用 Display.getRotation()
,但此信息已过时。
检测此变化以便我可以适本地重新定位我的相机预览的最佳方法是什么?
最佳答案
在你的 SurfaceHolder.Callback 中
orientationListener = createOrientationListener();
private OrientationEventListener createOrientationListener() {
return new OrientationEventListener(getActivity()) {
public void onOrientationChanged(int orientation) {
try {
if (orientation != OrientationEventListener.ORIENTATION_UNKNOWN) {
setCameraDisplayOrientation(getActivity().getWindowManager().getDefaultDisplay().getRotation());
}
} catch (Exception e) {
Log.w(TAG, "Error while onOrientationChanged", e);
}
}
};
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
orientationListener.enable();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
orientationListener.disable();
}
您的更改轮换方法必须管理不需要的双轮换
public void setCameraDisplayOrientation(int displayRotation) {
int degrees = 0;
switch (displayRotation) {
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 (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (cameraInfo.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (cameraInfo.orientation - degrees + 360) % 360;
}
if(result != currentSetRotation) {
currentSetRotation = result;
camera.setDisplayOrientation(result);
Log.d(TAG,"For displayRotation "+displayRotation+" we set a camera rotation of "+result);
}
}
另请参阅:Rotating phone quickly 180 degrees, camera preview turns upside down
关于android - 检测从 0 度到 180 度或 90 度到 270 度的屏幕旋转的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20542756/