How to get/detect screen size 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;
...
}
Recipe
Create a new Xamarin.Android application named ScreenSize. Edit Main.axml so that it contains two TextViews:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:text="Screen Width:"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/screenWidthDp" />
<TextView
android:text="Screen Height:"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/screenHeightDp" />
</LinearLayout>
Edit Activity1.cs, change the code in OnCreate to the following:
![enter image description here][1] private int ConvertPixelsToDp(float pixelValue) { var dp = (int) ((pixelValue)/Resources.DisplayMetrics.Density); return dp; }
Run the application. Depending on the device, it will display the screen height and width. The following screen shot is from a Galaxy Nexus:
[image link] http://i.stack.imgur.com/TQhba.png
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
There isn't currently a way from Xamarin.Forms itself but we have it implemented as PCL compatible interface in Xamarin.Forms.Labs which you can get from NuGet or source code from GitHub.
https://github.com/XForms/Xamarin-Forms-Labs
IDevice has IDisplay property with the information; height, width, pixel density for X & Y and couple of extension methods to calculate sized in inches.
Sample page for getting information from the device:
https://github.com/XForms/Xamarin-Forms-Labs/blob/master/samples/Xamarin.Forms.Labs.Sample/Pages/Services/ExtendedDeviceInfoPage.cs
#region Display information
var display = device.Display;
var displayFrame = new Frame();
if (display != null)
{
displayFrame.Content = new StackLayout()
{
Children =
{
new Label() { Text = display.ToString() },
new Label() { Text = string.Format("Screen width is\t {0:0.0} inches.", display.ScreenWidthInches()) },
new Label() { Text = string.Format("Screen height is\t {0:0.0} inches.", display.ScreenHeightInches()) },
new Label() { Text = string.Format("Screen diagonal size is\t {0:0.0} inches.", display.ScreenSizeInches()) }
}
};
}
else
{
displayFrame.Content = new Label() { TextColor = Color.Red, Text = "Device does not contain display information." };
}
stack.Children.Add(displayFrame);
#endregion
Creating an exact inch-by-inch frame on all platforms regardless of display properties:
https://github.com/XForms/Xamarin-Forms-Labs/blob/master/samples/Xamarin.Forms.Labs.Sample/Pages/Services/AbsoluteLayoutWithDisplayInfoPage.cs
public class AbsoluteLayoutWithDisplayInfoPage : ContentPage
{
public AbsoluteLayoutWithDisplayInfoPage(IDisplay display)
{
this.Title = "Absolute Layout With Display Info";
var abs = new AbsoluteLayout();
var inchX = display.WidthRequestInInches(1);
var inchY = display.HeightRequestInInches(1);
var originX = display.WidthRequestInInches(display.ScreenWidthInches() / 2);
var originY = display.HeightRequestInInches(display.ScreenHeightInches() / 2);
abs.Children.Add(new Label() { Text = "1\"x\"1\" blue frame" });
abs.Children.Add(new Frame()
{
BackgroundColor = Color.Navy,
},
new Rectangle(originX - inchX/2, originY - inchY/2, inchX, inchY));
abs.Children.Add(new Frame()
{
BackgroundColor = Color.White
},
new Rectangle(originX - inchX/16, originY - inchY/16, inchX/8, inchY/8));
this.Content = abs;
}
}
To get to the device info either set your DI resolver or use a static container. All 3 platforms have a singleton device calls with static CurrentDevice property:
resolverContainer.Register<IDevice>(t => WindowsPhoneDevice.CurrentDevice)
resolverContainer.Register<IDevice>(t => AppleDevice.CurrentDevice)
resolverContainer.Register<IDevice>(t => AndroidDevice.CurrentDevice)