簡體   English   中英

如何在Xamarin.Forms中獲取/檢測屏幕大小?

[英]How to get/detect screen size in Xamarin.Forms?

我正在嘗試重寫我為iOS編寫的應用程序。 我打算寫一個Android版本,但認為最好讓這個機會使用Xamarin.Forms。 一次做一頁,現在我被困在一個我需要獲得屏幕寬度和高度的頁面上。 有沒有人知道Xamarin.Forms中iOS的View.Frame.Width相當於什么?

更新:您可以將Xamarin.Essentials nuget包用於此目的和許多其他目的。

var width = DeviceDisplay.MainDisplayInfo.Width;
var height = DeviceDisplay.MainDisplayInfo.Height;

老答案:

有一種簡單的方法可以在Xamarin.Forms獲取屏幕的寬度和高度,並從應用程序的任何位置全局訪問它。 我會做這樣的事情:

1.在App.cs中創建兩個公共成員:

public static class App
{
    public static int ScreenWidth;
    public static int ScreenHeight;
    ...
}

2.在 MainActivity.cs (Android)或 AppDelegate.cs (iOS)中 設置值

安卓:

protected override void OnCreate(Bundle bundle)
{
    ...

    App.ScreenWidth = (int)Resources.DisplayMetrics.WidthPixels; // real pixels
    App.ScreenHeight = (int)Resources.DisplayMetrics.HeightPixels; // real pixels

    // App.ScreenWidth = (int)(Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density); // device independent pixels
    // App.ScreenHeight = (int)(Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density); // device independent pixels

    ...
}

iOS版:

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    ...

    App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;
    App.ScreenHeight = (int)UIScreen.MainScreen.Bounds.Height;

    ...
}

如果您使用的是xamarin表單,那么您可以在便攜式類庫(pcl)中找到當前屏幕的寬度和高度,如下所示。

對於寬度,你在pcl中使用它,

Application.Current.MainPage.Width

對於身高,你可以在pcl中做到這一點,

Application.Current.MainPage.Height

目前沒有Xamarin.Forms本身的方法,但我們將它實現為Xamarin.Forms.Labs中的PCL兼容接口,您可以從NuGet獲取或從GitHub獲取源代碼。

https://github.com/XForms/Xamarin-Forms-Labs

IDevice具有IDisplay屬性和信息; X和Y的高度,寬度,像素密度以及以英寸為單位計算的一對擴展方法。

從設備獲取信息的示例頁面:

https://github.com/XForms/Xamarin-Forms-Labs/blob/master/samples/Xamarin.Forms.Labs.Sample/Pages/Services/ExtendedDeviceInfoPage.cs

        #region Display information
        var display = device.Display;
        var displayFrame = new Frame();
        if (display != null)
        {
            displayFrame.Content = new StackLayout()
            {
                Children =
                {
                    new Label() { Text = display.ToString() },
                    new Label() { Text = string.Format("Screen width is\t {0:0.0} inches.", display.ScreenWidthInches()) },
                    new Label() { Text = string.Format("Screen height is\t {0:0.0} inches.", display.ScreenHeightInches()) },
                    new Label() { Text = string.Format("Screen diagonal size is\t {0:0.0} inches.", display.ScreenSizeInches()) }
                            }
                        };
        }
        else
        {
            displayFrame.Content = new Label() { TextColor = Color.Red, Text = "Device does not contain display information." };
        }

        stack.Children.Add(displayFrame); 
        #endregion

無論顯示屬性如何,在所有平台上創建精確的逐英寸框架:

https://github.com/XForms/Xamarin-Forms-Labs/blob/master/samples/Xamarin.Forms.Labs.Sample/Pages/Services/AbsoluteLayoutWithDisplayInfoPage.cs

public class AbsoluteLayoutWithDisplayInfoPage : ContentPage
{
    public AbsoluteLayoutWithDisplayInfoPage(IDisplay display)
    {
        this.Title = "Absolute Layout With Display Info";
        var abs = new AbsoluteLayout();
        var inchX = display.WidthRequestInInches(1);
        var inchY = display.HeightRequestInInches(1);
        var originX = display.WidthRequestInInches(display.ScreenWidthInches() / 2);
        var originY = display.HeightRequestInInches(display.ScreenHeightInches() / 2);

        abs.Children.Add(new Label() { Text = "1\"x\"1\" blue frame" });

        abs.Children.Add(new Frame()
            {
                BackgroundColor = Color.Navy,
            },
            new Rectangle(originX - inchX/2, originY - inchY/2, inchX, inchY));

        abs.Children.Add(new Frame()
            {
                BackgroundColor = Color.White
            },
            new Rectangle(originX - inchX/16, originY - inchY/16, inchX/8, inchY/8));

        this.Content = abs;
    }
}

要獲取設備信息,請設置DI解析器或使用靜態容器。 所有3個平台都具有靜態CurrentDevice屬性的單例設備調用:

resolverContainer.Register<IDevice>(t => WindowsPhoneDevice.CurrentDevice)
resolverContainer.Register<IDevice>(t => AppleDevice.CurrentDevice)
resolverContainer.Register<IDevice>(t => AndroidDevice.CurrentDevice)

食譜

創建一個名為ScreenSize的新Xamarin.Android應用程序。 編輯Main.axml,使其包含兩個TextView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:text="Screen Width:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/screenWidthDp" />
    <TextView
        android:text="Screen Height:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/screenHeightDp" />
</LinearLayout>
  1. 編輯Activity1.cs,將OnCreate中的代碼更改為以下內容:

    ![在此輸入圖像描述] [1] private int ConvertPixelsToDp(float pixelValue){var dp =(int)((pixelValue)/Resources.DisplayMetrics.Density); 返回dp; }

  2. 運行該應用程序。 根據設備的不同,它將顯示屏幕高度和寬度。 以下截圖來自Galaxy Nexus:

[圖片鏈接] http://i.stack.imgur.com/TQhba.png

在App文件中定義一個公共靜態變量

public static Size ScreenSize;

在調用App constructer之前,您應該在IOS和Android中初始化變量。 對於IOS,在FinishedLaunching方法中

App.ScreenSize = new Size(UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height);

而對於Android,在OnCreate函數中

            App.ScreenSize = new Xamarin.Forms.Size((int)(Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density), (int)(Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density));

更新未來的開發人員嘗試這樣做,或者沒有看到或錯過它。 Page類繼承自VisualElement,它現在有兩個屬性(碰巧可綁定在XAML中使用):

寬度 - 獲取此元素的當前渲染寬度。 這是一個只讀的可綁定屬性。 高度 - 獲取此元素的當前渲染高度。 這是一個只讀的可綁定屬性。

在您的頁面代碼隱藏中,您可以執行以下操作:

var myWidth = this.Width;
var myHeight = this.Height;

如果您需要知道它是否發生更改,請使用SizeChanged事件:

public MyPage()
{
    SizeChanged += OnSizeChanged;
}

private void OnSizeChanged(object sender, EventArgs e)
{
    var myWidth = this.Width;
    var myHeight = this.Height;
}

參考:Microsoft Docs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM