简体   繁体   English

获取屏幕尺寸 android 和 xamarin

[英]Getting screen size android with xamarin

I was wondering if anyone knows a simple way to get the height and width of an android screen size using c# in Xamarin. I need to get the screen size so that I can use it in one of my adapter classes.我想知道是否有人知道使用 Xamarin 中的 c# 获取 android 屏幕尺寸的高度和宽度的简单方法。我需要获取屏幕尺寸,以便我可以在我的适配器类之一中使用它。 I have tried using the display and the IWindowManager but without success.我曾尝试使用显示器和 IWindowManager 但没有成功。 Any help or a point in the right direction would be much appreciated.任何帮助或正确方向的一点将不胜感激。 Thanks in advance!!提前致谢!!

The answer that worked best for me was using 对我来说最有效的答案就是使用

var metrics = Resources.DisplayMetrics;

Thank you all for your help! 感谢大家的帮助!

Here a code snippet to get some info about the screen: 这是一个代码片段,用于获取有关屏幕的一些信息:

var metrics = new DisplayMetrics();
var windowManager = this.GetSystemService(Context.WindowService) as IWindowManager;
windowManager.DefaultDisplay.GetMetrics(metrics);

var height = metrics.HeightPixels;
var width = metrics.WidthPixels;
var xdpi = metrics.Xdpi;
var ydpi = metrics.Ydpi;
var density = metrics.Density;

The only thing that I'm not sure is the casing to the IWindowManager if can be done like this or maybe you have to do something much more specific. 我唯一不确定的是IWindowManager的外壳,如果可以这样做,或者你必须做一些更具体的事情。 Hope it will help you. 希望它会对你有所帮助。

var metrics = Resources.DisplayMetrics;

        height = metrics.HeightPixels;
        width = metrics.WidthPixels;

For real device screen size, use Xamarin.Essentials .对于真实设备屏幕尺寸,请使用Xamarin.Essentials

The difference between this and the accepted answer is that this will give your hardware accurate numbers, but that one will give you the size with the status and navigation bar reduced.这个和接受的答案之间的区别在于,这会给你的硬件准确的数字,但那个会给你状态和导航栏缩小的大小。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM