Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current screen width in xamarin forms

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.

like image 428
Tushar patel Avatar asked Aug 11 '16 08:08

Tushar patel


People also ask

How to get screen size 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.


3 Answers

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.

like image 117
Parth Patel Avatar answered Oct 16 '22 17:10

Parth Patel


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;
like image 73
EvZ Avatar answered Oct 16 '22 17:10

EvZ


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.

like image 31
Nicolas Bodin-Ripert Avatar answered Oct 16 '22 17:10

Nicolas Bodin-Ripert