How to get ttf font data from system fonts in java

2019-06-15 15:12发布

问题:

I have some ttf fonts installed on system.

I get that list using

GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()

This is not only ttf fonts but all fonts I guess. Eventually if I use:

Font.decode(fontName)

I can get awt.Font instance.

As far as I know Font is not connected to actual PhysicalFont, so how can I retrieve either ttf font file, or byte data from that ttf file for a font from that list or from awt.Font ? I am trying to retrieve a physical font data or anything similar. That data should be somewhere right?

The reason I need it is to eventually use with libGDX FreeTypeFontGenerator in order to generate BitmapFont

This has to work on windows, osx and linux.

回答1:

It isn't possible. The best you can do is using reflection, but it will only work with an Oracle JRE and accesses a private API so may break with any new Oracle release.

You could probably write a native lib to enumerate the fonts and their files.



回答2:

As @NateS pointed out, it appears what I want to achieve is not exactly possible.

So I will just share the solution I used in my case for now:

Which is this class: FontManager.java

This allows to pre-cache existing ttf files in known system locations based on your system, and then make a Map for fontName->fontFile type of connection. this then goes to preferences, and is loaded on next run.

Known issues are

  1. awt.Font has a known bug that is not able to read some ttf font family names on osx systems (mainly some arabic and chinese fonts)
  2. Did not test on Linux, will probably fail.
  3. First run might be slow if you have many fonts.

It would be ideal to write a native lib, but time is of an essence...