WPF截图显示不全且模糊问题求助(附相关代码)
解决WPF截图显示不全且模糊的问题
你这问题主要是两个核心点:高DPI环境下截图尺寸偏差,加上图像加载/显示时的DPI适配不到位,我帮你一步步搞定:
一、先搞定截图尺寸不全的问题
你现在用SystemParameters.PrimaryScreenWidth/Height拿的屏幕尺寸,在Windows开了缩放(比如125%、150%)的时候会被系统“缩水”,导致截出来的图比真实屏幕小,自然显示不全。
换个靠谱的截图方式:
用Screen.PrimaryScreen.Bounds获取真实的屏幕分辨率,这个值不受系统缩放影响。注意要先给WPF项目加个System.Windows.Forms的引用哦:
var screenBounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds; Bitmap bmp = new Bitmap(screenBounds.Width, screenBounds.Height); // 用using自动释放Graphics资源,避免内存泄漏 using (Graphics g = Graphics.FromImage(bmp)) { // 按真实屏幕的坐标和尺寸截图 g.CopyFromScreen(screenBounds.X, screenBounds.Y, 0, 0, screenBounds.Size); // 给Graphics设置和屏幕匹配的DPI,保证截图清晰度 g.DpiX = System.Windows.Forms.Screen.PrimaryScreen.DpiX; g.DpiY = System.Windows.Forms.Screen.PrimaryScreen.DpiY; } // 优先用PNG格式保存,比JPG清晰无压缩 bmp.Save(FullPath, System.Drawing.Imaging.ImageFormat.Png);
二、再解决图像模糊的问题
你的BitmapImage加载方式没考虑DPI适配,WPF的Image控件默认会跟着系统缩放调整,再加上截图本身的DPI不匹配,就容易模糊。
优化BitmapImage的加载逻辑:
BitmapImage bmI = new BitmapImage(); bmI.BeginInit(); bmI.UriSource = new Uri(FullPath); // 让BitmapImage用和截图一致的DPI bmI.DpiX = System.Windows.Forms.Screen.PrimaryScreen.DpiX; bmI.DpiY = System.Windows.Forms.Screen.PrimaryScreen.DpiY; // 用高质量插值模式,避免缩放模糊 bmI.InterpolationMode = System.Windows.Media.Imaging.BitmapInterpolationMode.HighQualityBicubic; // 可选:如果控件尺寸固定,按控件宽度解码,节省内存 // bmI.DecodePixelWidth = (int)Screen_Shot.ActualWidth; bmI.EndInit(); Screen_Shot.Source = bmI;
控件布局再加几个关键属性:
除了你已经设的Stretch,给Image控件加上这几个属性,清晰度会提升不少:
<Image x:Name="Screen_Shot" Stretch="Uniform" <!-- 用Uniform比Fill更能保持原图比例,不会拉伸变形 --> UseLayoutRounding="True" SnapsToDevicePixels="True" RenderOptions.BitmapScalingMode="HighQuality"/>
RenderOptions.BitmapScalingMode="HighQuality"会强制WPF用高质量的缩放算法,避免模糊。
三、最后补个重要配置
记得给你的WPF项目开启高DPI感知:右键项目→属性→应用程序→点击“查看Windows设置”,在打开的app.manifest里找到<application>标签下的dpiAware,改成:
<application xmlns="urn:schemas-microsoft-com:asm.v3"> <windowsSettings> <dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/PM</dpiAware> </windowsSettings> </application>
这样应用就能正确识别系统的缩放比例,不会出现尺寸偏差。
按这几步调整后,截图不全和模糊的问题应该就解决啦!
内容的提问来源于stack exchange,提问作者ofp212001305
相关产品推荐
相关产品推荐

