首页 > 解决方案 > 高 DPI 150%+ 上的 Graphics.DrawImage 仅绘制图像的一部分

问题描述

此问题发生在使用 175% 缩放或更高目标的 .Net 4.7.2 的 Windows 10 Creators Update 或更高版本上。此外,我们在 Program.cs 文件中调用 SetProcessDPIAware。

如果我们不这样称呼,那么字体在高 DPI 上看起来很糟糕,尤其是在 300% 下。

static class Program
{
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    private static extern bool SetProcessDPIAware();

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        //if (Environment.OSVersion.Version.Major >= 6)
        SetProcessDPIAware();

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

重要步骤我们还进入高级缩放设置并关闭“让窗口尝试修复应用程序以使其不模糊”功能......因为我们有用户将其关闭。 Windows 设置的图像

在下面的应用程序中,我们有 3 个 PictureBox 控件。最左边的 PictureBox 是来源,他的图像是一个以 96 dpi 创建的 PNG 文件。

用户单击中间 PictureBox 上方的按钮将源图像复制到 Metafile(用作绘图画布)并使用它来填充中间 PictureBox 的 Image 属性。在高 DPI 中,您可以看到图像大小不合适或仅将图像的一部分复制到元文件中。

最右侧 PictureBox 上方的按钮使用 Bitmap 作为绘图画布复制源 Image。他正确渲染为 175%。

申请结果图片

这是将源图像转换为元文件并将其粘贴到另一个 PictureBox 中的代码。

      private void DrawUsingMetafile()
    {
        try
        {
            Image img = this.pictureBox1.Image;

            Metafile mf = NewMetafile();

            using (Graphics gmf = Graphics.FromImage(mf))
            {
                gmf.DrawImage(img, 0, 0, img.Width, img.Height);
            }

            this.pictureBox2.Image = mf;
        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

}

        public static Metafile NewMetafile()
    {
        using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))  // offscreen device context
        {
            IntPtr hdc = g.GetHdc(); // gets released by g.Dispose() called by using g
            return new Metafile(hdc, EmfType.EmfPlusOnly);
        }
    }

任何想法为什么会发生这种情况?

标签: .netwinformsdpihdpi.net-4.7.2

解决方案


仅供参考 - 微软确认这是 .Net 4.8 中的一个错误。仅当您关闭“让 Windows 尝试修复应用程序以使其不模糊”功能时才会出现此问题。他们确认了该问题并对其进行了修补,但尚未发布该修复程序。


推荐阅读