具体方法
- 将下载到的字体文件复制到
assets/font
文件夹下 -
示例代码
```java public class MyTextView extends AppCompatTextView {
private static Hashtable
fontCache = new Hashtable<>();
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTextView(Context context) {
super(context);
init();
}
private void init() {
if (!isInEditMode()) {
Typeface tf = getTf();
setTypeface(tf);
}
}
public Typeface getTf() {
String tag = "font/DIN-Regular.ttf";
Typeface tf = fontCache.get(tag);
if(tf == null) {
try {
tf = Typeface.createFromAsset(getContext().getAssets(), tag);
} catch (Exception e) {
return null;
}
fontCache.put(tag, tf);
}
return tf;
}
}
示例图
字体提取工具
如果只引用第三方字体中的小部分,可使用此工具将引用部分提取到新的字体文件中,可优化加载字体文件大小
https://gitee.com/YpwCode/FontZip