ttf 文件字体提取

标签(空格分隔): ttf 、字体提取


场景:

如图,将“keep moving”区域的文案可以动态修改字体样式,“keep moving”文案也是可以动态修改

需求截图

方案:

1. 将字体文件打包放在App里面

这种方案就需要考虑字体文件大小,一般的字体文件大小如下:

英文字体:一般是几百KB
英文字体文件
中文字体:几M ~ 十几M
中文字体文件

显然,这种方案不管是中文还是英文字体,都增大app安装包。

2. 服务端提供字体文件,APP下载使用

2.1 如果是纯英文字体,不介意几百KB的下载流量,可以使用谷歌Android O提供的字体下载工具。

参考Google Sample

Download font sample
 private void requestDownload(String familyName) {
        QueryBuilder queryBuilder = new QueryBuilder(familyName)
                .withWidth(progressToWidth(mWidthSeekBar.getProgress()))
                .withWeight(progressToWeight(mWeightSeekBar.getProgress()))
                .withItalic(progressToItalic(mItalicSeekBar.getProgress()))
                .withBestEffort(mBestEffort.isChecked());
        String query = queryBuilder.build();

        Log.d(TAG, "Requesting a font. Query: " + query);
        FontRequest request = new FontRequest(
                "com.google.android.gms.fonts",
                "com.google.android.gms",
                query,
                R.array.com_google_android_gms_fonts_certs); 

        FontsContractCompat.FontRequestCallback callback = new FontsContractCompat
                .FontRequestCallback() {
            @Override
            public void onTypefaceRetrieved(Typeface typeface) {
                mDownloadableFontTextView.setTypeface(typeface);
            }

            @Override
            public void onTypefaceRequestFailed(int reason) {
            
            }
        };
        FontsContractCompat
                .requestFont(MainActivity.this, request, callback,
                        getHandlerThreadHandler());
    }
2.2 如果有中文字体,由于中文字体文件过大,可以进行字体提取
字体结构

这是一个已经较为复杂的衬线体拉丁字母,141 个控制点。


字母m

这是一个笔画不算太多的宋体汉字,181 个控制点。


中文 夷

由于字体文件的发展,目前的字体文件存在 直线和二次 B - 样条 (Bezier2Spline) 曲线、点阵字体、矢量字体和向量轮廓字体

字体文件结构

2.2.1 如果在字体中使用 TrueType 或 Postscipt 轮廓信息 ,以下表是实现字体功能所必需的。

标志位 名 称 描 述
Cmap Character to glyph mapping 字符代码到文字轮廓序号的映射表
Head Font header 文件头(信息) 表
Hhea Horizontal header 水平度量头信息
Hmtx Horizontal metrics 水平度量信息
Maxp Maximum profile 最大值描述表
Name Naming table 名字表
OS/ 2 OS/ 2 and Windows specific metrics OS/ 2 和 Windows 度量信息
Post PostScript information PostScript 打印机控制

2.2.2 与 TrueType 轮廓描述信息有关的表

标志位 名 称 描 述
Cvt Control Value Table 控制值表
Fpgm Font program 字体程序区
Glyf Glyph data 轮廓描述信息
Loca Index to location 轮廓数据索引表
prep CV T Program CV T 程序区

2.2.3 与 Postscipt 轮廓描述信息有关的表

标志位 名 称 描 述
CFF PostScript font program (compact font format) PostScript 字体程序区(压缩字体格式)
Fvar Apple’s font variations table Apple 字体转换表
MMSD Multiple master supplementary data 多主扩充数据
MMFX Multiple master font metrics 多主字体度量信息

2.2.4 支持垂直显示等高级字体印刷功能的表

标志位 名 称 描 述
BASE Baseline data 基线数据
GDEF Glyph definition data 笔划定义数据
GPOS Glyph positioning data 笔划位置数据
GSUB Glyph substitution data 笔划替换数据
J STF J ustification data 调整数据

2.2.5 与位图笔划有关的表

标志位 名 称 描 述
EBDT Embedded bitmap data 嵌入式位图数据
EBLC Embedded bitmap location data 嵌入式位图位置数据
EBSC Embedded bitmap scaling data 嵌入式位图缩放数据

2.2.6 其它一些 OpenType 描述表

标志位 名 称 描 述
DSIG Digital signature 数字标记
Gasp Grid - fitting/ Scan - conversion 网格适配/ 扫描转换过程表
Hdmx Horizontal device metrics 水平设备度量信息
Kern Kerning 紧排控制表
L TSH Linear threshold data 线性门限数据
PCL T PCL 5 data PCL 5 页面描述语言数据
VDMX Vertical device metrics 垂直设备度量信息
Vhea Vertical Metrics header 垂直度量头信息
vmtx Vertical Metrics 垂直度量信息

从文件中提取字体,主要要用到的几个表

  • cmap 字符代码到图元的映射 把字符代码映射为图元索引
  • glyf 图元数据 图元轮廓定义以及网格调整指令
  • loca 位置表索引 把元索引转换为图元的位置
字体提取流程
具体提取字体代码 参考
public void subsetFontFile(File fontFile, File outputFile, int nIters) throws IOException {
    FontFactory fontFactory = FontFactory.getInstance();
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(fontFile);
        byte[] fontBytes = new byte[(int)fontFile.length()];
        fis.read(fontBytes);
        Font[] fontArray = null;
        fontArray = fontFactory.loadFonts(fontBytes);
        Font font = fontArray[0];
        List<CMapTable.CMapId> cmapIds = new ArrayList<CMapTable.CMapId>();
        cmapIds.add(CMapTable.CMapId.WINDOWS_BMP);
        byte[] newFontData = null;
        Font newFont = font;
        if (subsetString != null) {
            Subsetter subsetter = new RenumberingSubsetter(newFont, fontFactory);
            subsetter.setCMaps(cmapIds, 1);
            List<Integer> glyphs = GlyphCoverage.getGlyphCoverage(font, subsetString);
            subsetter.setGlyphs(glyphs);
            Set<Integer> removeTables = new HashSet<Integer>();
            // Most of the following are valid tables, but we don't renumber them yet, so strip
            removeTables.add(Tag.GDEF);
            removeTables.add(Tag.GPOS);
            removeTables.add(Tag.GSUB);
            removeTables.add(Tag.kern);
            removeTables.add(Tag.hdmx);
            removeTables.add(Tag.vmtx);
            removeTables.add(Tag.VDMX);
            removeTables.add(Tag.LTSH);
            removeTables.add(Tag.DSIG);
            removeTables.add(Tag.vhea);
            // AAT tables, not yet defined in sfntly Tag class
            removeTables.add(Tag.intValue(new byte[]{'m', 'o', 'r', 't'}));
            removeTables.add(Tag.intValue(new byte[]{'m', 'o', 'r', 'x'}));
            subsetter.setRemoveTables(removeTables);
            newFont = subsetter.subset().build();
        }
        if (strip) {
            Subsetter hintStripper = new HintStripper(newFont, fontFactory);
            Set<Integer> removeTables = new HashSet<Integer>();
            removeTables.add(Tag.fpgm);
            removeTables.add(Tag.prep);
            removeTables.add(Tag.cvt);
            removeTables.add(Tag.hdmx);
            removeTables.add(Tag.VDMX);
            removeTables.add(Tag.LTSH);
            removeTables.add(Tag.DSIG);
            removeTables.add(Tag.vhea);
            hintStripper.setRemoveTables(removeTables);
            newFont = hintStripper.subset().build();
        }

        FileOutputStream fos = new FileOutputStream(outputFile);
        if (woff) {
            WritableFontData woffData = new WoffWriter().convert(newFont);
            woffData.copyTo(fos);
        } else if (eot) {
            WritableFontData eotData = new EOTWriter(mtx).convert(newFont);
            eotData.copyTo(fos);
        } else {
            fontFactory.serializeFont(newFont, fos);
        }
    } finally {
        if (fis != null) {
            fis.close();
        }
    }
}
public static List<Integer> getGlyphCoverage(Font font, String string) {
    CMapTable cmapTable = font.getTable(Tag.cmap);
    CMap cmap = getBestCMap(cmapTable);
    Set<Integer> coverage = new HashSet<Integer>();
    coverage.add(0);  // Always include notdef
    // TODO: doesn't support non-BMP scripts, should use StringCharacterIterator instead
    for (int i = 0; i < string.length(); i++) {
      int c = (string.charAt(i)) & 0xffff;
      int glyphId = cmap.glyphId(c);
      touchGlyph(font, coverage, glyphId);
    }
    List<Integer> sortedCoverage = new ArrayList<Integer>(coverage);
    Collections.sort(sortedCoverage);
    return sortedCoverage;
  }
  
  private static void touchGlyph(Font font, Set<Integer> coverage, int glyphId) {
    if (!coverage.contains(glyphId)) {
      coverage.add(glyphId);
      Glyph glyph = getGlyph(font, glyphId);
      if (glyph != null && glyph.glyphType() == GlyphType.Composite) {
        CompositeGlyph composite = (CompositeGlyph) glyph;
        for (int i = 0; i < composite.numGlyphs(); i++) {
          touchGlyph(font, coverage, composite.glyphIndex(i));
        }
      }
    }
  }
  
  private static CMap getBestCMap(CMapTable cmapTable) {
    for (CMap cmap : cmapTable) {
      if (cmap.format() == CMapFormat.Format12.value()) {
        return cmap;
      }
    }
    for (CMap cmap : cmapTable) {
      if (cmap.format() == CMapFormat.Format4.value()) {
        return cmap;
      }
    }
    return null;
  }

  private static Glyph getGlyph(Font font, int glyphId) {
    LocaTable locaTable = font.getTable(Tag.loca);
    GlyphTable glyfTable = font.getTable(Tag.glyf);
    int offset = locaTable.glyphOffset(glyphId);
    int length = locaTable.glyphLength(glyphId);
    return glyfTable.glyph(offset, length);
  }

疑问1:如果是中英文混合的文案怎么实现?

疑问2:QQ是怎么实现的?

QQ群聊

字体详情

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,761评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,953评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,998评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,248评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,130评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,145评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,550评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,236评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,510评论 1 291
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,601评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,376评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,247评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,613评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,911评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,191评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,532评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,739评论 2 335

推荐阅读更多精彩内容

  • 一、概念 参考网页字体Serif和Sans-serif的区别及浏览器字体的设置CSS Font知识整理总结 1.F...
    合肥黑阅读 6,044评论 0 12
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,074评论 25 707
  • 昨晚,“消失”了半年的发小大发在微信群里发了一条消息。 原话是:老子想通了!明天就回上海滩重建我的金融事业! 霎时...
    周白静阅读 921评论 0 3
  • N多n多幸运和智慧 才能带我们过好这一森 Try to improve one and seize the other!
    六六六六六六六六六阅读 148评论 0 0
  • 关注微信公众号“疯子五彩”,每天听我一个故事 今天这个故事, 讲的是两个男人之间的回忆。 这两个男人, 一位是我,...
    疯子五彩阅读 461评论 9 1