Android转换字体的工具类
2019-07-07 本文已影响0人
dashingqi
字体转换工具类
public class Utils {
private static final HashMap<String, Typeface> cache = new HashMap<>();
/**
* 字体的转换工具
* @param context
* @param assetPath
* @return
*/
public static Typeface getTypeFace(Context context, String assetPath) {
synchronized (cache) {
if (!cache.containsKey(assetPath)) {
try {
Typeface mTypeface = Typeface.createFromAsset(context.getAssets(), assetPath);
cache.put(assetPath, mTypeface);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
return cache.get(assetPath);
}
}
}
在Activity中使用
首先将字体文件放入到 assets文件夹中,然后读取文件夹中的字体文件 通过setTypeface方法设置字体样式。
这是收集了些日常常用的字体文件 https://pan.baidu.com/s/1zW1JvQ7p2uwIsBQUIlQecQ
private void initView() {
mTvText = findViewById(R.id.mTvText);
//设置特殊字体
mTvText.setTypeface(Utils.getTypeFace(MainActivity.this,"STXingkai.ttf"));
}