需求:橫屏拍攝的時候橫屏顯示,豎屏拍攝的時候豎屏顯示
思路:1、錄製視頻界面佈局不隨橫豎屏切換而變化。
2、橫豎屏切換佈局不變化的話,錄製的視頻的方向也就固定了。
解決:1、錄製視頻界面佈局不隨橫豎屏變化而變化的話,可以直接設定界面的方向固定爲豎直方向。
2、監聽手機旋轉狀態,根據旋轉角度來修改錄製視頻的方向。
具體代碼:
class MyOrientationEventListener extends OrientationEventListener {
private static final int SENSOR_ANGLE = 25;
public MyOrientationEventListener(Context context) {
super(context);
}
@Override
public void onOrientationChanged(int orientation) {
Log.d("ORIENTATIONA", "onOrientationChanged orientation=" + orientation);
if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) {
return; //手機平放時,檢測不到有效的角度
}
// 豎屏:0、180、360
// 橫屏:270、90
//下面是手機旋轉準確角度與四個方向角度(0 90 180 270)的轉換
if (orientation > 360 - SENSOR_ANGLE || orientation < SENSOR_ANGLE) {
photoOrientation = 0;
} else if (orientation > 90 - SENSOR_ANGLE && orientation < 90 + SENSOR_ANGLE) {
photoOrientation = 90;
} else if (orientation > 180 - SENSOR_ANGLE && orientation < 180 + SENSOR_ANGLE) {
photoOrientation = 180;
} else if (orientation > 270 - SENSOR_ANGLE && orientation < 270 + SENSOR_ANGLE) {
photoOrientation = 270;
} else {
return;
}
}
}
判斷手機是否支持重力感應,如果不支持,則設置不可用
listener = new MyOrientationEventListener(this);
if (listener.canDetectOrientation()) {
listener.enable();
}else {
listener.disable();
}
然後在設置錄製視頻方向前獲取角度,根據角度設置錄製視頻方向
//手機豎直方向
if (MediaRecorderActivity.getPhotoOrientation() == 0 ||
MediaRecorderActivity.getPhotoOrientation() == 180) {
mMediaRecorder.setOrientationHint(or);
}
//手機後置攝像頭朝左
if (MediaRecorderActivity.getPhotoOrientation() == 90){
mMediaRecorder.setOrientationHint(180);
}
public static int getPhotoOrientation(){
return photoOrientation;
}
這篇博客主要是提供一個思路,具體需求具體處理。