Absolute Dimensions Of App Screen - Xamarin.Forms

In this article, we are going to learn how to get the exact dimensions of the app screen. First, let us understand the need of absolute dimensions of an app screen.

 Assume that you set a button size of 200*50 on a screen of 320*480. Then, if the app is installed on a device of 1240*2240, then the size of the button will look very small and weird, so the button should be increased in width and height accordingly. There are many ways to achieve this but for very beginners, the best option is to set button dimensions proportionate to the screen size and to set proportionate values we have need absolute screen values.

Now, let us learn how to get them.

Steps in Brief

  1. Where to place the code for getting dimensions.
  2. Code to get the exact dimensions (height and width).
  3. How to get the values to PCL.
  4. How to assign these values to Views

Steps in Detail

Code to get Dimensions (Height and Width)

In Android

  1. var widthPixels = Resources.DisplayMetrics.WidthPixels;//getting the width in pixels  

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.Forms. We have to do all this because for one unit there will be a number of pixels present and views do not understand pixels and if we set the dimensions based on pixels then views consider them as units only and the size will be very large. To understand see the following example.

Example: Assume a button is to be set at 150 units width and our device is 340 units. Also, our screen pixel density is 32px.

Then, these required 150 units make 150*32 = 480px.

The total screen width of 340 units make 340*32 = 10880px.

Now, if you set the width of the button as 480 assuming the total width as 10800, the Xamarin.Forms understands this as 480 units instead of 480px and the button will be very large. So, to get a clear value of width, we have to convert the total pixels into units.

Note
If you are developing the application in Xamarin.Android then you should use the pixels -- you don't need units.

  1. var scale = Resources.DisplayMetrics.Density;//density i.e., pixels per inch or cms  
  2. var width = (double)((widthPixels - 0.5f) / scale);//width in units  
  3. var heightPixels = Resources.DisplayMetrics.HeightPixels;////getting the height in pixels  
  4. var height = (double)((heightPixels - 0.5f) / scale);//height in units  

In iOS

For iOS in both Xamarin.Forms and Xamarin.iOS, we can use the following directly without any conversions unlike in Android.

  1. var width = (int)UIScreen.MainScreen.Bounds.Width;//width in units  
  2. var height = (int)UIScreen.MainScreen.Bounds.Height;//height in units  
Where to place the code for getting dimensions

Here, to get the absolute dimensions we can use the code at the app startup or we can create a dependency service and call that service when required. Mostly we follow the former one as it is not suggested to call the dependency service every time as we might use these values on almost every page, based on our requirement. So considering that we are using at the app start, we have to place the code.

For Android

After global::Xamarin.Forms.Forms.Init(this, bundle); method and before LoadApplication(new App()); method in MainActivity.cs

For iOS

After global::Xamarin.Forms.Forms.Init(); method and before LoadApplication(new App()); method in AppDelegate.cs

How to get the values to PCL

By creating static variables in App.cs page assign this value at app start and use them until the user closes the application.

In App.cs

Create global and static variables.

  1. public static int screenHeight, screenWidth;  
How to Assign these values to Views

Use the obtained values while setting the height request and width request to the view as follows:

  1. viewObject.WidthRequest = (App.screenHeight * 10) / 100;  
  2. viewObject.HeghtRequest = (App.screenWidth * 90) / 100;  

Coding Part

Let us get to the coding part.

In App.cs / App.xaml.cs

C#

  1. using System;  
  2. using PageAbsoluteDimensions.Views;  
  3. using Xamarin.Forms;  
  4. using Xamarin.Forms.Xaml;  
  5.   
  6. [assembly: XamlCompilation(XamlCompilationOptions.Compile)]  
  7. namespace PageAbsoluteDimensions  
  8. {  
  9.     public partial class App : Application  
  10.     {  
  11.         public static int screenHeight, screenWidth;  
  12.         public App()  
  13.         {  
  14.             InitializeComponent();  
  15.   
  16.             MainPage = new TestPage();  
  17.         }  
  18.   
  19.         protected override void OnStart()  
  20.         {  
  21.             // Handle when your app starts  
  22.         }  
  23.   
  24.         protected override void OnSleep()  
  25.         {  
  26.             // Handle when your app sleeps  
  27.         }  
  28.   
  29.         protected override void OnResume()  
  30.         {  
  31.             // Handle when your app resumes  
  32.         }  
  33.     }  
  34. }  

In Android → in MainActivity.cs

C#

  1. using System;  
  2. using Android.App;  
  3. using Android.Content.PM;  
  4. using Android.Runtime;  
  5. using Android.Views;  
  6. using Android.Widget;  
  7. using Android.OS;  
  8.   
  9. namespace PageAbsoluteDimensions.Droid  
  10. {  
  11.     [Activity(Label = "PageAbsoluteDimensions", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]  
  12.     public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity  
  13.     {  
  14.         protected override void OnCreate(Bundle bundle)  
  15.         {  
  16.             TabLayoutResource = Resource.Layout.Tabbar;  
  17.             ToolbarResource = Resource.Layout.Toolbar;  
  18.   
  19.             base.OnCreate(bundle);  
  20.   
  21.             global::Xamarin.Forms.Forms.Init(this, bundle);  
  22.             #region For screen Height & Width  
  23.             var pixels = Resources.DisplayMetrics.WidthPixels;  
  24.             var scale = Resources.DisplayMetrics.Density;  
  25.             var dps = (double)((pixels - 0.5f) / scale);  
  26.             var ScreenWidth = (int)dps;  
  27.             App.screenWidth = ScreenWidth;  
  28.             pixels = Resources.DisplayMetrics.HeightPixels;  
  29.             dps = (double)((pixels - 0.5f) / scale);  
  30.             var ScreenHeight = (int)dps;  
  31.             App.screenHeight = ScreenHeight;  
  32.             #endregion  
  33.             LoadApplication(new App());  
  34.         }  
  35.     }  
  36. }  

In iOS → AppDelegate.cs

C#

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4.   
  5. using Foundation;  
  6. using UIKit;  
  7.   
  8. namespace PageAbsoluteDimensions.iOS  
  9. {  
  10.     // The UIApplicationDelegate for the application. This class is responsible for launching the   
  11.     // User Interface of the application, as well as listening (and optionally responding) to   
  12.     // application events from iOS.  
  13.     [Register("AppDelegate")]  
  14.     public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate  
  15.     {  
  16.         //  
  17.         // This method is invoked when the application has loaded and is ready to run. In this   
  18.         // method you should instantiate the window, load the UI into it and then make the window  
  19.         // visible.  
  20.         //  
  21.         // You have 17 seconds to return from this method, or iOS will terminate your application.  
  22.         //  
  23.         public override bool FinishedLaunching(UIApplication app, NSDictionary options)  
  24.         {  
  25.             global::Xamarin.Forms.Forms.Init();  
  26.             #region For Screen Height & Width  
  27.             App.screenWidth = (int)UIScreen.MainScreen.Bounds.Width;  
  28.             App.screenHeight = (int)UIScreen.MainScreen.Bounds.Height;  
  29.             #endregion  
  30.             LoadApplication(new App());  
  31.   
  32.             return base.FinishedLaunching(app, options);  
  33.         }  
  34.     }  
  35. }  

In PCL → TestPage.xaml.cs

XAML

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ContentPage   
  3.     xmlns="http://xamarin.com/schemas/2014/forms"   
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"   
  5.     x:Class="PageAbsoluteDimensions.Views.TestPage">  
  6.     <ContentPage.Content>  
  7.         <AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">  
  8.             <StackLayout AbsoluteLayout.LayoutBounds="0,0,1,0.1" AbsoluteLayout.LayoutFlags="All" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">  
  9.                 <Label Text="Test Page" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"></Label>  
  10.             </StackLayout>  
  11.             <StackLayout AbsoluteLayout.LayoutBounds="1,1,1,0.9" AbsoluteLayout.LayoutFlags="All" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">  
  12.                 <Button x:Name="submitButton" Text="Get Dimensions" BackgroundColor="Teal" TextColor="Maroon" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Clicked="GetFullDimensions"></Button>  
  13.             </StackLayout>  
  14.         </AbsoluteLayout>  
  15.     </ContentPage.Content>  
  16. </ContentPage>  

In PCL → TestPage.xaml

C#

  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. using Xamarin.Forms;  
  5.   
  6. namespace PageAbsoluteDimensions.Views  
  7. {  
  8.     public partial class TestPage : ContentPage  
  9.     {  
  10.         public TestPage()  
  11.         {  
  12.             InitializeComponent();  
  13.             #region for dimension Adjustments  
  14.             submitButton.HeightRequest = (App.screenHeight * 20) / 100;  
  15.             submitButton.WidthRequest = (App.screenWidth * 70) / 100;  
  16.             #endregion  
  17.         }  
  18.   
  19.         private async void GetFullDimensions(object sender, EventArgs e)  
  20.         {  
  21.             await DisplayAlert("Page Dimensions Are""Height = " + (App.screenHeight.ToString()) + ". \n Width = " + (App.screenWidth) + ". ""Ok");  
  22.         }  
  23.     }  
  24. }  

Conclusion

We can manage the dynamic sizes with LayoutOptions, Padding and Margin, Grid, AbsoluteLayout, and RelativeLayout. For some rare scenarios and for beginners who have not mastered the above mentioned layouts, they can use this method for easy UI designing.

References

  • For Downloading this sample,

    https://code.msdn.microsoft.com/Absolute-dimensions-of-App-06f35f9d/

  • To learn about more Xamarin tutorials please visit.

    https://code.msdn.microsoft.com/Absolute-dimensions-of-App-06f35f9d/
    https://xamarindevelopers.blogspot.com/ 


    or

    https://code.msdn.microsoft.com/Absolute-dimensions-of-App-06f35f9d/
    https://www.c-sharpcorner.com/members/pvspreddy/articles


    To learn about other Technologies/tutorials please visit,

    https://code.msdn.microsoft.com/Absolute-dimensions-of-App-06f35f9d/
    https://allsoftwaredevelopments.blogspot.com/


Similar Articles