美文网首页
Android转换字体的工具类

Android转换字体的工具类

作者: dashingqi | 来源:发表于2019-07-07 11:57 被阅读0次

字体转换工具类

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"));
    }

相关文章

网友评论

      本文标题:Android转换字体的工具类

      本文链接:https://www.haomeiwen.com/subject/ofdbhctx.html