不同分辨率不同DPI下的自适应

不同分辨率不同DPI下的自适应

WPF应用程序在不同分辨率下要做到自适应需要一般可以在前台使用ViewBox作为最外层容器,里面使用一个固定尺寸的容器。在后台需要动态设置窗体的尺寸,宽度和高度设置我这里采用静态类静态方法来调用:

public class WindowUtil
    {
     
        const double DpiPercent = 96;

        /// 
        /// 获取自适应窗体宽度
        /// 
        /// 窗体原宽度
        /// 自适应宽度
        public static double GetAutoWidth(double sourcewidth)
        {
     
            if (IsDpiChanged() == false)
            {
     
                return sourcewidth * SystemParameters.PrimaryScreenWidth / 1920;
            }
            else
            {
     
                return sourcewidth * GetScreenWidth() / 1920 ;
            }
        }

        /// 
        /// 获取自适应窗体高度
        /// 
        /// 窗体原高度
        /// 自适应高度
        public static double GetAutoHeight(double sourceheight)
        {
     
            if (IsDpiChanged() == false)
            {
     
                return sourceheight * SystemParameters.PrimaryScreenHeight / 1080;
            }
            else
            {
     
                return sourceheight * GetScreenHeight() / 1080;
            }
        }

        /// 
        /// DPI是否更改
        /// 
        /// 
        private static bool IsDpiChanged()
        {
     
            using (Graphics graphics = Graphics.FromHwnd(IntPtr.Zero))
            {
     
                float dpiX = graphics.DpiX;
                float dpiY = graphics.DpiY;
                if (dpiX != DpiPercent && dpiY != DpiPercent)
                {
     
                    return true;
                }
                else
                {
     
                    return false;
                }
            }
        }

        /// 
        /// 获取相应DPI下的屏幕高度
        /// 
        /// 
        public static double GetScreenHeight()
        {
     
            double height = 0;
            var screen = Screen.FromHandle(IntPtr.Zero);
            using (Graphics currentGraphics = Graphics.FromHwnd(IntPtr.Zero))
            {
     
                double dpiXRatio = currentGraphics.DpiX / DpiPercent;
                double dpiYRatio = currentGraphics.DpiY / DpiPercent;
                height = screen.Bounds.Height / dpiYRatio;
            }
            return height;
        }

        /// 
        /// 获取相应DPI下的屏幕宽度
        /// 
        /// 
        public static double GetScreenWidth()
        {
     
            double width = 0;
            var screen = Screen.FromHandle(IntPtr.Zero);
            using (Graphics currentGraphics = Graphics.FromHwnd(IntPtr.Zero))
            {
     
                double dpiXRatio = currentGraphics.DpiX / DpiPercent;
                double dpiYRatio = currentGraphics.DpiY / DpiPercent;
                width = screen.Bounds.Width / dpiYRatio;
            }
            return width;
        }
}

你可能感兴趣的:(WPF,WPF,自适应,DPI)