Android 如何在 Xamarin.Forms 中获取/检测屏幕尺寸?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24465513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:14:03  来源:igfitidea点击:

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

androidiosxamarin.iosxamarinxamarin.forms

提问by dmc

I am trying to rewrite an app that I wrote for iOS. I was going to write an android version but thought It'd be better to make this the opportunity to use Xamarin.Forms. Doing it one page at a time, now I'm stuck on a page where I need to get the screen's width and height. Does anyone know the equivalent of iOS' View.Frame.Width in Xamarin.Forms?

我正在尝试重写我为 iOS 编写的应用程序。我打算写一个 android 版本,但认为最好让这个有机会使用 Xamarin.Forms。一次做一页,现在我被困在需要获取屏幕宽度和高度的页面上。有谁知道 Xamarin.Forms 中 iOS 的 View.Frame.Width 的等价物?

采纳答案by SKall

There isn't currently a way from Xamarin.Forms itself but we have it implemented as PCL compatible interface in Xamarin.Forms.Labs which you can get from NuGet or source code from GitHub.

目前没有来自 Xamarin.Forms 本身的方法,但我们将它实现为 Xamarin.Forms.Labs 中的 PCL 兼容接口,您可以从 NuGet 或从 GitHub 获取源代码。

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

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

IDevice has IDisplay property with the information; height, width, pixel density for X & Y and couple of extension methods to calculate sized in inches.

IDevice 具有包含信息的 IDisplay 属性;X 和 Y 的高度、宽度、像素密度以及几种以英寸为单位计算尺寸的扩展方法。

Sample page for getting information from the device:

从设备获取信息的示例页面:

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

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

Creating an exact inch-by-inch frame on all platforms regardless of display properties:

无论显示属性如何,都可以在所有平台上创建精确的一英寸一英寸的框架:

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

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;
    }
}

To get to the device info either set your DI resolver or use a static container. All 3 platforms have a singleton device calls with static CurrentDevice property:

要获取设备信息,请设置您的 DI 解析器或使用静态容器。所有 3 个平台都有一个带有静态 CurrentDevice 属性的单例设备调用:

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

回答by kaolick

Update:You can use Xamarin.Essentialsnuget package for this and many other purposes.

更新:您可以将Xamarin.Essentialsnuget 包用于此目的和许多其他目的。

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

Old answer:

旧答案:

There is an easy way to get the screen's width and height in Xamarin.Formsand access it globally from everywhere in your app. I'd do something like this:

有一种简单的方法可以获取屏幕的宽度和高度,Xamarin.Forms并从应用程序的任何地方全局访问它。我会做这样的事情:

1. Create two public members in your App.cs:

1. 在你的 App.cs 中创建两个公共成员:

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

2. Set the values in yourMainActivity.cs(Android) or yourAppDelegate.cs(iOS):

2. 在您的MainActivity.cs(Android) 或(iOS) 中设置值AppDelegate.cs

Android:

安卓:

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:

IOS:

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

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

    ...
}

回答by Tushar patel

If you are using xamarin forms, then you can find width and height of current screen in portable class library(pcl) like below.

如果您使用的是 xamarin 表单,那么您可以在便携式类库(pcl)中找到当前屏幕的宽度和高度,如下所示。

For Width you use this in pcl,

对于宽度,您在 pcl 中使用它,

Application.Current.MainPage.Width

For height you can do this in pcl,

对于高度,您可以在 pcl 中执行此操作,

Application.Current.MainPage.Height

回答by TheEmperorDeveloper

Recipe

食谱

Create a new Xamarin.Android application named ScreenSize. Edit Main.axml so that it contains two TextViews:

创建一个名为 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. Edit Activity1.cs, change the code in OnCreate to the following:

    ![enter image description here][1] private int ConvertPixelsToDp(float pixelValue) { var dp = (int) ((pixelValue)/Resources.DisplayMetrics.Density); return dp; }

  2. Run the application. Depending on the device, it will display the screen height and width. The following screen shot is from a Galaxy Nexus:

  1. 编辑Activity1.cs,将OnCreate中的代码改成如下:

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

  2. 运行应用程序。根据设备,它将显示屏幕高度和宽度。以下屏幕截图来自 Galaxy Nexus:

[image link] http://i.stack.imgur.com/TQhba.png

[图片链接] http://i.stack.imgur.com/TQhba.png

回答by sof98789

In your App file define a public static variable

在您的 App 文件中定义一个公共静态变量

public static Size ScreenSize;

You should initialise the variable both in IOS and Android before calling the App constructer. For IOS, in FinishedLaunching method

在调用 App 构造器之前,您应该在 IOS 和 Android 中初始化变量。对于 IOS,在 FinishedLaunching 方法中

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

and For Android, in OnCreate function

对于 Android,在 OnCreate 函数中

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

回答by Duane

Updating for future developers trying to do this that either haven't looked or missed it. The Page class inherits from VisualElement, which now has two properties (which happen to be bindable for use in XAML):

为未来尝试这样做的开发人员更新,这些开发人员要么没有看过,要么错过了。Page 类继承自 VisualElement,它现在有两个属性(碰巧可绑定以在 XAML 中使用):

Width - Gets the current rendered width of this element. This is a read-only bindable property. Height - Gets the current rendered height of this element. This is a read-only bindable property.

宽度 - 获取此元素的当前呈现宽度。这是一个只读的可绑定属性。高度 - 获取此元素的当前渲染高度。这是一个只读的可绑定属性。

in your page codebehind you would just do something like:

在您的页面代码隐藏中,您只需执行以下操作:

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

if you needed to know if it changes, use the SizeChanged event:

如果您需要知道它是否发生变化,请使用 SizeChanged 事件:

public MyPage()
{
    SizeChanged += OnSizeChanged;
}

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

ref: Microsoft Docs

参考:微软文档