[英]Get the current screen orientation in MonoDroid
我需要在MonoDroid中當前設置的屏幕方向。 它必須檢測它是風景,肖像還是反向風景和反向肖像。
諸如WindowManager.DefaultDisplay.Rotation之類的方法並不總是返回正確的結果。
我在這里找到了用Java編寫的答案: 如何獲取Android設備的當前方向(ActivityInfo.SCREEN_ORIENTATION_ *)?
這是相應的MonoDroid C#翻譯:
private ScreenOrientation GetScreenOrientation() {
ScreenOrientation orientation;
SurfaceOrientation rotation = WindowManager.DefaultDisplay.Rotation;
DisplayMetrics dm = new DisplayMetrics();
WindowManager.DefaultDisplay.GetMetrics(dm);
if ((rotation == SurfaceOrientation.Rotation0 || rotation == SurfaceOrientation.Rotation180) && dm.HeightPixels > dm.WidthPixels
|| (rotation == SurfaceOrientation.Rotation90 || rotation == SurfaceOrientation.Rotation270) && dm.WidthPixels > dm.HeightPixels) {
// The device's natural orientation is portrait
switch (rotation) {
case SurfaceOrientation.Rotation0:
orientation = ScreenOrientation.Portrait;
break;
case SurfaceOrientation.Rotation90:
orientation = ScreenOrientation.Landscape;
break;
case SurfaceOrientation.Rotation180:
orientation = ScreenOrientation.ReversePortrait;
break;
case SurfaceOrientation.Rotation270:
orientation = ScreenOrientation.ReverseLandscape;
break;
default:
orientation = ScreenOrientation.Portrait;
break;
}
} else {
// The device's natural orientation is landscape or if the device is square
switch (rotation) {
case SurfaceOrientation.Rotation0:
orientation = ScreenOrientation.Landscape;
break;
case SurfaceOrientation.Rotation90:
orientation = ScreenOrientation.Portrait;
break;
case SurfaceOrientation.Rotation180:
orientation = ScreenOrientation.ReverseLandscape;
break;
case SurfaceOrientation.Rotation270:
orientation = ScreenOrientation.ReversePortrait;
break;
default:
orientation = ScreenOrientation.Landscape;
break;
}
}
return orientation;
}
如此簡單和常見的任務有很多代碼,但是效果很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.