0

I want to load a font from a compiled resource which is the program itself. I can load it using AddFontMemResourceEx when I was using GDI. However, direct 2D has it own Dwrite API which is not compatible with GDI. The official document suggests using CreateCustomFontFileReference + CreateCustomFontCollection. Could anyone give me an example how to do it?

bunglehead
  • 1,104
  • 1
  • 14
  • 22
  • A bit of googling: https://github.com/microsoft/Windows-classic-samples/tree/master/Samples/DirectWriteCustomFontSets – Simon Mourier Jan 29 '20 at 11:52
  • @SimonMourier Thanks for helping, don’t you think the example is too overkill? Could you write a function just “Install the resource font to system”? –  Jan 29 '20 at 11:59
  • The `AddFontMemResourceEx` function, if used properly, will effectively install the font for the duration of the executable that calls it. That is to say, if that function is successful, you can use the font *as though it were* installed. – Adrian Mole Jan 29 '20 at 14:31
  • @AdrianMole I just tried it. It does not work with dwrite. I successfully got the handle. But I can not use the font in TextFomat struct. It still used the default one. –  Jan 29 '20 at 15:55
  • This [document](https://learn.microsoft.com/en-us/windows/win32/directwrite/custom-font-sets-win10) describes various ways in which you can use custom fonts in your app. Or on earlier Windows versions: https://learn.microsoft.com/en-us/windows/win32/directwrite/custom-font-collections – Drake Wu Jan 30 '20 at 02:54
  • 1
    Another way is to use IDWriteInMemoryFontFileLoader, but that probably requires recent Windows releases. If you need it to work with Windows 7+ you'll have to go with a custom loader. – bunglehead Jan 30 '20 at 08:14

1 Answers1

1

Take a look at the DirectWriteCustomFontSets sample in the microsoft/windows-classic-samples repo on GitHub (here). It demonstrates five scenarios using a custom font set, and based on your question it sounds like case 4 would apply to your situation: "Creates a custom font set using font data contained in in-memory buffers."

For this scenario, the key interface is IDWriteInMemoryFontFileLoader, which was added in the Windows 10 Creators Update (spring 2017).

The specific files in the sample project that will be most relevant are:

  • CustomFontSetManager.h/.cpp — this includes members applicable to the other scenarios as well
  • BinaryResources.h/.cpp
  • Document.h/.cpp — this is described as simulating a document file containing the font data (e.g., a .doc file), but it could be any kind of binary.
Peter Constable
  • 2,707
  • 10
  • 23