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