代码
public class HaiyanFontUtil {
private static Font definedFont = null;
public static Font getDefinedFont(String type, float size) {
String fontUrl = Thread.currentThread().getContextClassLoader()
.getResource("").getPath() + "fonts" + File.separator + type;
if (definedFont == null) {
try {
File file = new File(fontUrl);
definedFont = Font.createFont(Font.TRUETYPE_FONT, file);
definedFont = definedFont.deriveFont(size);
} catch (FontFormatException | IOException e) {
e.printStackTrace();
return new java.awt.Font("宋体", Font.PLAIN, 50);
}
}
return definedFont;
}
public static void main(String[] args) {
Font font = getDefinedFont("STXINGKA.TTF", 50);
}
}
如果 pom.xml
src/main/resources
true
则会导致 字体文件 打包时 损坏不可用
修改
src/main/resources
true
fonts/**
src/main/resources
false
fonts/**
过滤时排处 fonts 文件夹下的 文件
参考
Maven 打包 项目中的资源文件损坏打不开 https://blog.csdn.net/qing_mei_xiu/article/details/80661216
Java引用外部字体即自定义字体文件 https://blog.csdn.net/nahancy/article/details/75482418