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
- Where to place the code for getting dimensions.
- Code to get the exact dimensions (height and width).
- How to get the values to PCL.
- How to assign these values to Views
Steps in Detail
Code to get Dimensions (Height and Width)
In Android
- var widthPixels = Resources.DisplayMetrics.WidthPixels;
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.
- var scale = Resources.DisplayMetrics.Density;
- var width = (double)((widthPixels - 0.5f) / scale);
- var heightPixels = Resources.DisplayMetrics.HeightPixels;
- var height = (double)((heightPixels - 0.5f) / scale);
In iOS
For iOS in both Xamarin.Forms and Xamarin.iOS, we can use the following directly without any conversions unlike in Android.
- var width = (int)UIScreen.MainScreen.Bounds.Width;
- var height = (int)UIScreen.MainScreen.Bounds.Height;
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.
- 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:
- viewObject.WidthRequest = (App.screenHeight * 10) / 100;
- viewObject.HeghtRequest = (App.screenWidth * 90) / 100;
Coding Part
Let us get to the coding part.
In App.cs / App.xaml.cs
C#
- using System;
- using PageAbsoluteDimensions.Views;
- using Xamarin.Forms;
- using Xamarin.Forms.Xaml;
-
- [assembly: XamlCompilation(XamlCompilationOptions.Compile)]
- namespace PageAbsoluteDimensions
- {
- public partial class App : Application
- {
- public static int screenHeight, screenWidth;
- public App()
- {
- InitializeComponent();
-
- MainPage = new TestPage();
- }
-
- protected override void OnStart()
- {
-
- }
-
- protected override void OnSleep()
- {
-
- }
-
- protected override void OnResume()
- {
-
- }
- }
- }
In Android → in MainActivity.cs
C#
- using System;
- using Android.App;
- using Android.Content.PM;
- using Android.Runtime;
- using Android.Views;
- using Android.Widget;
- using Android.OS;
-
- namespace PageAbsoluteDimensions.Droid
- {
- [Activity(Label = "PageAbsoluteDimensions", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
- public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
- {
- protected override void OnCreate(Bundle bundle)
- {
- TabLayoutResource = Resource.Layout.Tabbar;
- ToolbarResource = Resource.Layout.Toolbar;
-
- base.OnCreate(bundle);
-
- global::Xamarin.Forms.Forms.Init(this, bundle);
- #region For screen Height & Width
- var pixels = Resources.DisplayMetrics.WidthPixels;
- var scale = Resources.DisplayMetrics.Density;
- var dps = (double)((pixels - 0.5f) / scale);
- var ScreenWidth = (int)dps;
- App.screenWidth = ScreenWidth;
- pixels = Resources.DisplayMetrics.HeightPixels;
- dps = (double)((pixels - 0.5f) / scale);
- var ScreenHeight = (int)dps;
- App.screenHeight = ScreenHeight;
- #endregion
- LoadApplication(new App());
- }
- }
- }
In iOS → AppDelegate.cs
C#
- using System;
- using System.Collections.Generic;
- using System.Linq;
-
- using Foundation;
- using UIKit;
-
- namespace PageAbsoluteDimensions.iOS
- {
-
-
-
- [Register("AppDelegate")]
- public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
- {
-
-
-
-
-
-
-
- public override bool FinishedLaunching(UIApplication app, NSDictionary options)
- {
- global::Xamarin.Forms.Forms.Init();
- #region For Screen Height & Width
- App.screenWidth = (int)UIScreen.MainScreen.Bounds.Width;
- App.screenHeight = (int)UIScreen.MainScreen.Bounds.Height;
- #endregion
- LoadApplication(new App());
-
- return base.FinishedLaunching(app, options);
- }
- }
- }
In PCL → TestPage.xaml.cs
XAML
- <?xml version="1.0" encoding="UTF-8"?>
- <ContentPage
- xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- x:Class="PageAbsoluteDimensions.Views.TestPage">
- <ContentPage.Content>
- <AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
- <StackLayout AbsoluteLayout.LayoutBounds="0,0,1,0.1" AbsoluteLayout.LayoutFlags="All" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
- <Label Text="Test Page" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"></Label>
- </StackLayout>
- <StackLayout AbsoluteLayout.LayoutBounds="1,1,1,0.9" AbsoluteLayout.LayoutFlags="All" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
- <Button x:Name="submitButton" Text="Get Dimensions" BackgroundColor="Teal" TextColor="Maroon" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" Clicked="GetFullDimensions"></Button>
- </StackLayout>
- </AbsoluteLayout>
- </ContentPage.Content>
- </ContentPage>
In PCL → TestPage.xaml
C#
- using System;
- using System.Collections.Generic;
-
- using Xamarin.Forms;
-
- namespace PageAbsoluteDimensions.Views
- {
- public partial class TestPage : ContentPage
- {
- public TestPage()
- {
- InitializeComponent();
- #region for dimension Adjustments
- submitButton.HeightRequest = (App.screenHeight * 20) / 100;
- submitButton.WidthRequest = (App.screenWidth * 70) / 100;
- #endregion
- }
-
- private async void GetFullDimensions(object sender, EventArgs e)
- {
- await DisplayAlert("Page Dimensions Are", "Height = " + (App.screenHeight.ToString()) + ". \n Width = " + (App.screenWidth) + ". ", "Ok");
- }
- }
- }
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/