在C#(Xamarin跨平台App)中获取屏幕尺寸可以通过以下方式实现:
DeviceDisplay.MainDisplayInfo
属性获取主显示设备的信息,包括屏幕尺寸和分辨率。using Xamarin.Essentials;
var mainDisplayInfo = DeviceDisplay.MainDisplayInfo;
var screenWidth = mainDisplayInfo.Width;
var screenHeight = mainDisplayInfo.Height;
DependencyService
在各个平台上调用相应的原生API获取屏幕尺寸。首先,在共享代码项目中创建一个接口,定义获取屏幕尺寸的方法:
public interface IScreenSizeService
{
Size GetScreenSize();
}
然后,在各个平台的原生项目中实现该接口:
在Android项目中,创建一个类ScreenSizeService
,实现IScreenSizeService
接口:
using Xamarin.Forms;
using YourAppName.Droid;
using Android.Content;
using Android.Util;
[assembly: Dependency(typeof(ScreenSizeService))]
namespace YourAppName.Droid
{
public class ScreenSizeService : IScreenSizeService
{
public Size GetScreenSize()
{
var displayMetrics = Android.App.Application.Context.Resources.DisplayMetrics;
var screenWidth = displayMetrics.WidthPixels / displayMetrics.Density;
var screenHeight = displayMetrics.HeightPixels / displayMetrics.Density;
return new Size(screenWidth, screenHeight);
}
}
}
在iOS项目中,创建一个类ScreenSizeService
,实现IScreenSizeService
接口:
using Xamarin.Forms;
using YourAppName.iOS;
using UIKit;
[assembly: Dependency(typeof(ScreenSizeService))]
namespace YourAppName.iOS
{
public class ScreenSizeService : IScreenSizeService
{
public Size GetScreenSize()
{
var bounds = UIScreen.MainScreen.Bounds;
var screenWidth = bounds.Width;
var screenHeight = bounds.Height;
return new Size(screenWidth, screenHeight);
}
}
}
最后,在共享代码中调用DependencyService
获取屏幕尺寸:
var screenSizeService = DependencyService.Get<IScreenSizeService>();
var screenSize = screenSizeService.GetScreenSize();
var screenWidth = screenSize.Width;
var screenHeight = screenSize.Height;
这样就可以在C#(Xamarin跨平台App)中获取屏幕尺寸了。
领取专属 10元无门槛券
手把手带您无忧上云