Mario
Mario

Reputation: 14741

Fonts added with AddFontResourceEx are not working in GDI+

AddFontResourceEx returns 1 for each font, but the fonts are not accesible in GDI+ (Tested with VS2015 and Windows 10, also on Windows 2008 R2 Server).

If I install the fonts manually with Windows Fonts Explorer everything works ok. It seems that GDI+ cannot find the fonts added with AddFontResourceEx or AddFontResource, any idea how can I get this working?

I use CodeJock Library which uses GDI+ fonts for rendering XAML graphics, so I cannot control how to fonts are created.

int n = 0;
CPathW pw;

pw.Combine(theApp.m_strMyAppFolder, _T("Roboto-Light.ttf"));
n =AddFontResourceEx(pw, FR_PRIVATE, nullptr);

pw.Combine(theApp.m_strMyAppFolder, _T("Roboto-Thin.ttf"));
AddFontResourceEx(pw, FR_PRIVATE, nullptr);

pw.Combine(theApp.m_strMyAppFolder, _T("Roboto-Regular.ttf"));
AddFontResourceEx(pw, FR_PRIVATE, nullptr);

pw.Combine(theApp.m_strMyAppFolder, _T("Ubuntu-R.ttf"));
AddFontResourceEx(pw, FR_PRIVATE, nullptr);

pw.Combine(theApp.m_strMyAppFolder, _T("Ubuntu-L.ttf"));
AddFontResourceEx(pw, FR_PRIVATE, nullptr);

::SendNotifyMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);

Upvotes: 0

Views: 2237

Answers (1)

zett42
zett42

Reputation: 27756

For GDI+ you need to use class PrivateFontCollection which solves a similar purpose as AddFontResourceEx() with FR_PRIVATE.

There is already an example at the documentation for PrivateFontCollection::AddFontFile() so I'm just commenting on that.

The example adds fonts from the Windows Fonts folder to the private font collection which is pointless because these fonts are available anyway. You already load the fonts from the application folder in your AddFontResourceEx() example so you can use the same paths for PrivateFontCollection::AddFontFile().

Another thing to note is that the PrivateFontCollection object should stay around as long as the application is running and should not be recreated everytime one wants to draw text with these fonts. A good place would be a member variable in the application class. This should be obvious but the example makes it appear as if you have to recreate the PrivateFontCollection everytime. This would be a major performance hit.

Edit:

I use CodeJock Library which uses GDI+ fonts for rendering XAML graphics

The PrivateFontCollection is propably not so easy to use in this context, as it doesn't make the fonts globally available in your application, but has to be used as constructor argument of Font. But you wrote that you don't control how the fonts are created by CodeJock.

Maybe CodeJock supports private fonts directly in the XAML, see this example which is for C# but maybe works for CodeJock too.

Upvotes: 3

Related Questions