'Xamarin android get screen size in px

Hi i am trying to get the screen size of device I have tried this code: layout.Width; layout.Height; but the width and the height are returning 0,0 anybody knows how to get the screen size?



Solution 1:[1]

Xamarin "DetectScreenSize" Recipe:

var metrics = Resources.DisplayMetrics;
var widthInDp = ConvertPixelsToDp(metrics.WidthPixels);
var heightInDp = ConvertPixelsToDp(metrics.HeightPixels);

private int ConvertPixelsToDp(float pixelValue)
{
    var dp = (int) ((pixelValue)/Resources.DisplayMetrics.Density);
    return dp;
}

re: https://github.com/xamarin/recipes/blob/master/Recipes/android/resources/device_specific/detect_screen_size/DetectScreenSize/Activity1.cs

Solution 2:[2]

using Xamarin.Essentials

  var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
  var realHeightInPx = mainDisplayInfo.Height;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SushiHangover
Solution 2 Amin Keshavarzian