I am creating one Xamarin Forms project and I got stuck in finding the current screen width according to the different device.
I know how it can be done in android and ios but need a way to find the width in portable.
For Xamarin. Forms in Android, we get the width and height values in pixels. To get the exact size of the screen we have to get the pixel density and on dividing the pixels with density we get the length and breadth of the screen in units and we use these units to set the sizes of the views of Xamarin.
Xamarin. Essentials provides a single cross-platform API that works with any iOS, Android, or UWP application that can be accessed from shared code no matter how the user interface is created. See the platform & feature support guide for more information on supported operating systems.
You can try this Application.Current.MainPage.Width
in my case this worked and i am able to find the device width in portable project itself.
I know it is an old thread but worth mentioning that recently Xamarin.Essentials NuGet pakage was released and there is a useful class DeviceDisplay
in there that should handle this task for you.
The documentation can be found here.
Usage example:
// Get Metrics
var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
// Orientation (Landscape, Portrait, Square, Unknown)
var orientation = mainDisplayInfo.Orientation;
// Rotation (0, 90, 180, 270)
var rotation = mainDisplayInfo.Rotation;
// Width (in pixels)
var width = mainDisplayInfo.Width;
// Width (in xamarin.forms units)
var xamarinWidth = width / mainDisplayInfo.Density;
// Height (in pixels)
var height = mainDisplayInfo.Height;
// Screen density
var density = mainDisplayInfo.Density;
Common code (in App.xaml.cs)
public static int ScreenHeight {get; set;}
public static int ScreenWidth {get; set;}
Android part (in MainActivity.cs, in the OnCreate method)
App.ScreenHeight = (int) (Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density);
App.ScreenWidth = (int) (Resources.DisplayMetrics.WidthPixels / Resources.DisplayMetrics.Density);
iOS part (in AppDelegate.cs, in the FinishedLaunching method)
App.ScreenHeight = (int)UIScreen.MainScreen.Bounds.Height;
App.ScreenWidth = (int)UIScreen.MainScreen.Bounds.Width;
So App.ScreenHeight and App.ScreenWidth will be initialized when the App will be launched, then you will be able to use them anywhere in the common code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With