Xamarin.Essentials:裝置顯示資訊

DeviceDisplay 類別提供應用程式執行所在的裝置畫面計量資訊,並可要求防止畫面在應用程式正在執行時休眠。

開始使用

若要開始使用此 API,請閱讀 入門指南Xamarin.Essentials,以確保連結庫已正確安裝並設定在您的專案中。

使用 DeviceDisplay

在類別中新增 的 Xamarin.Essentials 參考:

using Xamarin.Essentials;

主要顯示資訊

除了基本的裝置資訊外,DeviceDisplay 類別也包含裝置畫面和方向的相關資訊。

// Get Metrics
var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;

// Orientation (Landscape, Portrait, Square, Unknown)
var orientation = mainDisplayInfo.Orientation;

// Rotation (0, 90, 180, 270)
var rotation = mainDisplayInfo.Rotation;

// Width (in pixels)
var width = mainDisplayInfo.Width;

// Height (in pixels)
var height = mainDisplayInfo.Height;

// Screen density
var density = mainDisplayInfo.Density;

DeviceDisplay 類別也會公開可以訂閱的事件,只要畫面計量有任何變更,就會觸發該事件:

public class DisplayInfoTest
{
    public DisplayInfoTest()
    {
        // Subscribe to changes of screen metrics
        DeviceDisplay.MainDisplayInfoChanged += OnMainDisplayInfoChanged;
    }

    void OnMainDisplayInfoChanged(object sender, DisplayInfoChangedEventArgs  e)
    {
        // Process changes
        var displayInfo = e.DisplayInfo;
    }
}

讓畫面保持開啟

DeviceDisplay 類別公開稱為 KeepScreenOnbool 屬性,其可設定為嘗試防止裝置顯示關閉或鎖定。

public class KeepScreenOnTest
{
    public void ToggleScreenLock()
    {
        DeviceDisplay.KeepScreenOn = !DeviceDisplay.KeepScreenOn;
    }
}

平台差異

沒有差異。

API

Channel 9YouTube 上尋找更多 Xamarin 影片。