Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 536
dmc Avatar asked Jun 28 '14 09:06

dmc


People also ask

How do I screen size in xamarin?

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.

What is xamarin essentials?

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.


2 Answers

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;

    ...
}
like image 191
kaolick Avatar answered Sep 18 '22 06:09

kaolick


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

For Width you use this in pcl,

Application.Current.MainPage.Width

For height you can do this in pcl,

Application.Current.MainPage.Height
like image 27
Tushar patel Avatar answered Sep 17 '22 06:09

Tushar patel