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;
...
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…