Graphics.DrawImage在高DPI 150%+上仅绘制图像的一部分

问题描述 投票:1回答:1

此问题在Windows 10 Creators Update或更高版本上使用175%缩放或更高目标的.Net 4.7.2。此外,我们在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());
    }
}

重要步骤我们还进入“高级缩放设置”,然后关闭“让窗口尝试修复应用程序,以免它们模糊不清”的功能……因为我们有用户将其关闭。Image of the Windows Setting

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

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

最右边PictureBox上方的按钮使用位图作为绘图画布复制源图像。他的渲染正确率为175%。

Picture of Application Results

这是将源图像转换为图元文件并将其粘贴到另一个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);
        }
    }

任何想法为什么会这样?

.net winforms dpi hdpi .net-4.7.2
1个回答
0
投票

仅供参考-Microsoft确认这是.Net 4.8中的错误。仅当您关闭功能“让窗口尝试修复应用程序,以使它们不会模糊”]]时,问题才会发生。他们确认了该问题并进行了修补,但尚未发布该修复程序。

© www.soinside.com 2019 - 2024. All rights reserved.