Java中有没有办法从Font对象中获取本机字体名称?
我使用此代码获取我的字体,Font.decode("Serif")并且出于调试目的,我想知道使用的本机字体.
它可能不那么简单.某些字体由许多物理字体组成,对不同的字形使用不同的物理字体.
例如,在我的Windows系统上,Serif字体使用12种物理字体:
以下代码可以将字体分解为其物理组件.它使用反射黑客来访问sun.awt.Font2D对象,因此使用风险自负(适用于Oracle Java 6u37):
import java.awt.Font;
import java.lang.reflect.Method;
import java.util.Locale;
import sun.font.CompositeFont;
import sun.font.Font2D;
import sun.font.PhysicalFont;
public class FontTester
{
public static void main(String... args)
throws Exception
{
Font font = new Font("Serif", Font.PLAIN, 12);
describeFont(font);
}
private static void describeFont(Font font)
throws Exception
{
Method method = font.getClass().getDeclaredMethod("getFont2D");
method.setAccessible(true);
Font2D f = (Font2D)method.invoke(font);
describeFont2D(f);
}
private static void describeFont2D(Font2D font)
{
if (font instanceof CompositeFont)
{
System.out.println("Font '" + font.getFontName(Locale.getDefault()) + "' is composed of:");
CompositeFont cf = (CompositeFont)font;
for (int i = 0; i < cf.getNumSlots(); i++)
{
PhysicalFont pf = cf.getSlotFont(i);
describeFont2D(pf);
}
}
else
System.out.println("-> " + font);
}
}
Run Code Online (Sandbox Code Playgroud)