下面的代碼應該生成一個大小為 200 毫米 x 100 毫米和一個 180 毫米 x 80 毫米的中心矩形的增強型 Windows 元檔案 (EMF)。從 Windows 表單應用程式運行時,它可以作業。從控制臺應用程式運行時,大小(或框架)不正確:它幾乎是寬度和高度的兩倍。
可能導致不同行為的控制臺應用程式和 Windows 表單應用程式之間有什么不同?糾正 EMF 大小/幀需要進行哪些更改_
兩個應用程式都運行:
- .NET Core 3.1(我嘗試了 .NET 6 和 .NET Framework,結果相同)
- System.Drawing.Common 4.5.1(我嘗試了更新版本,結果相同)
我也嘗試使用毫米作為頁面和框架單位。它有同樣的效果。此外,尺寸減少了 5%。在所有情況下,我都將 EMF 檔案插入 Microsoft Word 并從那里獲取大小。
正如我所經歷的那樣,元檔案對使用的顯示幕有一種奇怪的依賴性,這可能與我以 200% 的比例使用 HiDPI 顯示幕有關。
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace MetafileDotNot
{
internal class Program
{
static void Main()
{
using (Graphics offScreenGraphics = Graphics.FromHwndInternal(IntPtr.Zero))
{
float mmToPixel = offScreenGraphics.DpiX / 25.4f;
using (Metafile metaFile = new Metafile(
"test.emf",
offScreenGraphics.GetHdc(),
new RectangleF(0, 0, 200 * mmToPixel, 100 * mmToPixel),
MetafileFrameUnit.Pixel,
EmfType.EmfPlusDual
))
using (Graphics graphics = Graphics.FromImage(metaFile))
{
graphics.PageUnit = GraphicsUnit.Pixel;
graphics.FillRectangle(Brushes.DarkBlue, new RectangleF(10 * mmToPixel, 10 * mmToPixel, 180 * mmToPixel, 80 * mmToPixel));
}
}
}
}
}
更新
如果我將顯示幕的比例設定為 150%,則不正確的尺寸約為所需尺寸的 1.5 倍,而不是 2 倍。所以它遵循顯示縮放。
此外,offScreenGraphics.DpiX控制臺應用程式為 96,Windows 表單應用程式為 192 和 144,顯示比例分別為 200% 和 150%。
uj5u.com熱心網友回復:
感謝漢斯·帕桑特。他的鏈接非常有幫助。
因此,即使 EMF 是一種與解析度無關的圖形檔案格式,螢屏(可能是主螢屏)的解析度和 DPI 也會影響結果。基本上,EMF 使用螢屏的物理單位。所以對于 HiDPI 螢屏,它取決于螢屏縮放。
要修復它,應用程式需要在DPI 感知模式下運行。請參閱下文,了解如何實作它。
如果改為在DPI 虛擬化模式下運行,EMF 幀的行為與 EMF 內容不同,結果不正確。這很奇怪,可能是一個錯誤。
我還注意到,沒有任何結果符合 Microsoft 發布的 EMF 和 EMF 標準。如果是這樣,它們將無法在 Microsoft Office 中正常作業。現在它在 Microsoft Word 中運行良好。
DPI 感知模式
SetProcessDPIAware()在應用程式開始時呼叫它:
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool SetProcessDPIAware();
或使用應用程式清單:
<?xml version="1.0" encoding="utf-8"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" >
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<asmv3:application>
<asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
<dpiAware>true</dpiAware>
</asmv3:windowsSettings>
</asmv3:application>
</assembly>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/443398.html
