首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Windows 8 風格應用開發入門:裝置方向感測器程式設計

     編輯:關於.NET

Windows 8 裝置內建方向感測器,可偵測六種方向狀態。透過 SimpleOrientationSensor 與 DisplayProperties API,應用可即時回應裝置旋轉,調整遊戲操作、介面佈局或鎖定方向。

六種方向狀態對照表

裝置方向感測器值Windows 鍵位置參考
水平向上NotRotatedWindows 鍵在下方
垂直向左Rotated90DegreesCounterclockwiseWindows 鍵在右側
水平向下Rotated180DegreesCounterclockwiseWindows 鍵在上方
垂直向右Rotated270DegreesCounterclockwiseWindows 鍵在左側
螢幕朝上Faceup平放桌面
螢幕朝下Facedown螢幕朝下

方向狀態對照表 Windows鍵位置參考1 Windows鍵位置參考2 Windows鍵位置參考3 Windows鍵位置參考4

取得當前裝置方向

步驟 1:初始化感測器

var sensor = SimpleOrientationSensor.GetDefault();

步驟 2:註冊方向變更事件

sensor.OrientationChanged += Sensor_OrientationChanged;

步驟 3:處理方向變更

private void Sensor_OrientationChanged(SimpleOrientationSensor sender, 
    SimpleOrientationSensorOrientationChangedEventArgs e) {
    var orientation = e.Orientation;
    // 更新 UI 或遊戲邏輯
    UpdateOrientationDisplay(orientation);
}

private void UpdateOrientationDisplay(SimpleOrientation orientation) {
    string text = "";
    switch (orientation) {
        case SimpleOrientation.NotRotated: text = "水平向上"; break;
        case SimpleOrientation.Rotated90DegreesCounterclockwise: text = "垂直向左"; break;
        case SimpleOrientation.Rotated180DegreesCounterclockwise: text = "水平向下"; break;
        case SimpleOrientation.Rotated270DegreesCounterclockwise: text = "垂直向右"; break;
        case SimpleOrientation.Faceup: text = "螢幕朝上"; break;
        case SimpleOrientation.Facedown: text = "螢幕朝下"; break;
    }
    // UI 更新需在 UI 執行緒
    Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
        txtOrientation.Text = text;
    });
}

感測器初始化程式碼 事件處理程式碼 方向顯示更新方法

DisplayProperties 類別關鍵成員

成員類型說明
OrientationChanged事件方向變更時觸發
CurrentOrientation唯讀屬性目前裝置方向
NativeOrientation唯讀屬性裝置原生方向
AutoRotationPreferences可讀寫屬性應用偏好方向(模擬器不支援)

鎖定應用方向

設定 DisplayProperties.AutoRotationPreferences 限制支援的旋轉方向:

// 僅支援橫向
DisplayProperties.AutoRotationPreferences = DisplayOrientations.Landscape;

// 支援橫向與縱向
DisplayProperties.AutoRotationPreferences = DisplayOrientations.Landscape | 
    DisplayOrientations.Portrait;

應用場景

  • 遊戲:根據裝置傾斜控制角色移動
  • 閱讀器:鎖定縱向提供舒適閱讀
  • 導航:鎖定橫向對應車載支架
  • 相機:根據方向自動調整預覽畫面

方向感測器讓應用具備空間感知能力。下一章將介紹語義縮放控件,實現大量資料的縮放導航。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved