在實際開發中, 我們需要把字體的名字和字體做一一對應的映射關係, 然後需要通過可配置的方式加載自定義的字體. 所以就有了這個需求, 我們來實現.
首先我們定義一個自定義加載子類的工具類:
import java.awt.Font;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 字體工具類, 獲取需要的字體
*/
public class FontUtil {
/**
* 所有字體配置
*/
private static Map<String, String> fontNameMap = new HashMap<String, String>();
/**
* 默認字體的大小
*/
private static final float defaultFontSize = 20f;
static {
//加載配置文件
Properties properties = new Properties();
// 使用properties對象加載輸入流, 編碼使用GBK
try {
properties.load(new InputStreamReader(FontUtil.class.getClassLoader().getResourceAsStream("font.properties"), "GBK"));
} catch (IOException e) {
System.err.println("font.properties 配置文件不存在");
}
//獲取key對應的value值
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
if (key != null && value != null) {
fontNameMap.put(String.valueOf(key), String.valueOf(value));
}
}
}
/**
* 獲取定義的字體
*
* @param key 字體的名字
* @return
*/
public static Font getConfigFont(String key) {
return getConfigFont(key, defaultFontSize);
}
/**
* 獲取自定義的字體
*
* @param key 字體的名字
* @param fontSize 字體的大小
* @return
*/
public static Font getConfigFont(String key, float fontSize) {
String fontUrl = fontNameMap.get(key);
if (fontUrl == null) {
throw new RuntimeException("名字是:" + key + "的字體配置不存在");
}
//默認先看是不是系統字體
Font font = new Font(fontUrl, Font.PLAIN, (int) fontSize);
//判斷當前字體存不存在
if ("Dialog.plain".equals(font.getFontName())) {
try (
InputStream is = new FileInputStream(new File(fontUrl));
) {
Font definedFont = Font.createFont(Font.TRUETYPE_FONT, is);
//設置字體大小,float型
definedFont = definedFont.deriveFont(fontSize);
return definedFont;
} catch (Exception e) {
throw new RuntimeException("名字是:" + key + "的字體不存在");
}
}
return font;
}
}
第二部再就是寫測試代碼:
import java.awt.*;
public class Demo {
public static void main(String[] args) throws Exception {
Font a = FontUtil.getConfigFont("A");
System.out.println(a.getName() + "~" + a.getSize());
Font b = FontUtil.getConfigFont("B", 100);
System.out.println(b.getName() + "~" + b.getSize());
Font c = FontUtil.getConfigFont("C");
System.out.println(c.getFontName());
Font d = FontUtil.getConfigFont("D");
}
}
運行, 第四個字體不存在, 拋出異常 , 其他的都正常處理了, A, B都加載了自己配置的字體.
環境配置, 在resources裏面新建一個字體配置文件: font.properties 內容如下:
#字體的配置文件,等號前是字體名字,等號後是字體的路徑
A=D:/logs/蘋方黑體-準-簡.ttf
B=D:/logs/蘋方黑體-中粗-簡.ttf
C=宋體
D=宋體22222
本來是幫別人寫的代碼, 最後不要了, 就直接開源出來了.