1

我需要将一组字体添加到PrivateFontCollection. 由于某种原因,这个任务应该通过使用AddMemoryFont函数来完成。

    var fontCollectionFromMemory = new PrivateFontCollection();
    var fontCollectionFromFile = new PrivateFontCollection();
    foreach (var file in Directory.GetFiles(@"C:\Windows\Fonts", "*.ttf"))
    {
        using (var stream = File.OpenRead(file))
        {
            var fontData = new byte[stream.Length];
            stream.Read(fontData, 0, fontData.Length);
            var fontDataPtr = Marshal.AllocCoTaskMem(fontData.Length);
            try
            {
                Marshal.Copy(fontData, 0, fontDataPtr, fontData.Length);
                fontCollectionFromMemory.AddMemoryFont(fontDataPtr, fontData.Length);
                Thread.Sleep(100);
            }
            finally
            {
                Marshal.FreeCoTaskMem(fontDataPtr);
            }
        }

        // fontCollectionFromFile.AddFontFile(file);
    }
    Console.WriteLine($"PrivateFontCollection's size(filled via AddMemoryFont): {fontCollectionFromMemory.Families.Length}");
    Console.WriteLine($"PrivateFontCollection's size(filled via AddFontFile): {fontCollectionFromFile.Families.Length}");

运行上面的代码后,我得到以下输出:

PrivateFontCollection's size(filled via AddMemoryFont): 34
PrivateFontCollection's size(filled via AddFontFile): 0

这个结果非常令人困惑……

如果我取消注释以下行:

fontCollectionFromFile.AddFontFile(file);

然后我得到:

PrivateFontCollection's size(filled via AddMemoryFont): 166
PrivateFontCollection's size(filled via AddFontFile): 198

这个结果也令人困惑。

如何解释这些结果?什么是正确的使用方法PrivateFontCollection.AddMemoryFont

环境:

  • Windows 10 家庭版

  • .Net 核心 2.2.106

  • System.Drawing.Common 4.7.0

4

0 回答 0