gpt4 book ai didi

xamarin.forms - 如何以 xamarin 形式检测设备的大小

转载 作者:行者123 更新时间:2023-12-04 03:49:54 25 4
gpt4 key购买 nike

您如何检测设备是小还是大?
我不需要检测是否是平板电脑。
这个概念取自 https://devblogs.microsoft.com/xamarin/styling-for-multiple-device-resolutions/
我们使用下面的方法并相应地加载适当的样式,但是因为我没有考虑密度它是不准确的。
我如何改进或重写此方法,以便它为我提供更好的结果并更准确地检测设备是大还是小。
当前

const int smallWightResolution = 768;
const int smallHeightResolution = 1280;

public static bool IsASmallDevice()
{
// Get Metrics
var mainDisplayInfo = Xamarin.Essentials.DeviceDisplay.MainDisplayInfo;

// Width (in pixels)
var width = mainDisplayInfo.Width;

// Height (in pixels)
var height = mainDisplayInfo.Height;
return (width <= smallWightResolution && height <= smallHeightResolution);
}
尝试使用密度但不知道公式是什么
public static bool IsSmallDevice()
{
//we don't support tablet so tablet don't apply.

int smallWidthResolution = 768;
int smallHeightResolution = 1280;
double screenWidth;
double screenHeight;
bool isSmallDevice;

var metrics = Xamarin.Essentials.DeviceDisplay.MainDisplayInfo;

switch (Xamarin.Forms.Device.RuntimePlatform)
{
case Xamarin.Forms.Device.Android:
//Android not sure how to sort of correctly detect if is a small device
screenWidth = (metrics.Width - 0.5f) / metrics.Density;
screenHeight = (metrics.Height - 0.5f) / metrics.Density;
isSmallDevice = "???????";
break;
case Xamarin.Forms.Device.iOS:
//ios no changes
isSmallDevice = metrics.Width <= smallWidthResolution
&& metrics.Height <= smallHeightResolution;
break;
}

return isSmallDevice;
}
更新
Huawei P9 Android 7.0
Density=2.5
Width=1080
Height=2160
ScreenHeight(Calculated)=864
ScreenWidth(Calculated)=432


Samsung A20 Android (new phone)
Density=2
Width=720
Height=1560
ScreenHeight(Calculated)=780
ScreenWidth(Calculated)=360
有什么建议?

最佳答案

回答
我建议使用 Xamarin.Essentials NuGet Package检索屏幕的宽度、高度和密度,然后使用以下公式:

  • 屏幕宽度 = 宽度/密度
  • 屏幕高度 = 高度/密度

  • 代码
    using Xamarin.Essentials;

    // **** Example Screen Sizes ****
    // iPhone SE 2nd Gen (aka iPhone 8), Width 750, Density 2, Width/Density 375
    // iPhone 11, Width 828, Density 2, Width/Density 414
    // Pixel 3, Width 1080, Density 2.75, Width/Density 392.7
    // Galaxy S5, Width 1080, Density 3, Width/Density 360
    // Galaxy Nexus, Width 720, Density 2, Width/Density 360
    public static double ScreenWidth { get; } = DeviceDisplay.MainDisplayInfo.Width / DeviceDisplay.MainDisplayInfo.Density;
    public static double ScreenHeight { get; } = DeviceDisplay.MainDisplayInfo.Height / DeviceDisplay.MainDisplayInfo.Density;

    public static bool IsSmallScreen { get; } = ScreenWidth <= 360;
    示例应用程序
    这是我在 GitTrends 中使用上述代码的方式应用程序:
    https://github.com/brminnick/GitTrends/blob/aa0c0a2d53dab7306514287533330b4a3bfbf609/GitTrends/Services/XamarinFormsService.cs#L11-L18

    关于xamarin.forms - 如何以 xamarin 形式检测设备的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64567353/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com