如何在Unity中获取Windows缩放与布局百分比?
在Unity中获取Windows缩放与布局百分比的实现
可以实现,以下是两种可行的方案:
方案一:借助System.Windows.Forms类库
该方案逻辑和你提供的原生C#代码类似,但需要在Unity项目中添加对System.Windows.Forms.dll的引用(路径通常为C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Windows.Forms.dll,可根据你的.NET版本调整)。
代码示例:
#if UNITY_STANDALONE_WIN using System.Windows.Forms; public static class ScalingHelper { public static int GetWindowsScaling() { return (int)(100f * Screen.PrimaryScreen.Bounds.Width / SystemInformation.PrimaryMonitorSize.Width); } } #endif
方案二:调用Windows原生API(推荐)
无需额外引用类库,直接通过P/Invoke调用Windows系统API,更适合Unity打包后的Windows应用,还能支持多显示器场景下获取当前窗口所在显示器的缩放比例。
代码示例:
#if UNITY_STANDALONE_WIN using System; using System.Runtime.InteropServices; using UnityEngine; public static class WindowsScalingHelper { [DllImport("user32.dll")] private static extern bool GetDpiForMonitor(IntPtr hmonitor, MonitorDpiType dpiType, out uint dpiX, out uint dpiY); private enum MonitorDpiType : int { MDT_Effective_DPI = 0 } [DllImport("user32.dll")] private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags); private const uint MONITOR_DEFAULTTOPRIMARY = 0x00000001; public static int GetWindowsScalingPercentage() { IntPtr windowHandle = Application.windowHandle; IntPtr monitorHandle = MonitorFromWindow(windowHandle, MONITOR_DEFAULTTOPRIMARY); if (GetDpiForMonitor(monitorHandle, MonitorDpiType.MDT_Effective_DPI, out uint dpiX, out _)) { // 标准DPI为96,计算缩放百分比 return (int)((dpiX / 96f) * 100); } // 获取失败时默认返回100% return 100; } } #endif
注意事项
- 两种方案仅适用于Windows平台,用
#if UNITY_STANDALONE_WIN宏包裹代码可避免其他平台编译报错。 - 方案一在打包时需确保
System.Windows.Forms.dll被正确包含到输出目录中。
内容的提问来源于stack exchange,提问作者Yidi
相关产品推荐
相关产品推荐

