Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.Forms and access it globally from everywhere in your app. I'd do something like this:

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

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

2. Set the values in your MainActivity.cs (Android) or your AppDelegate.cs (iOS):

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:

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

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

    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...