Android 字体资产 vs 字体资源 (API 26)

Android font assets vs font resources (API 26)

要在 android 应用程序中使用自定义字体,似乎有两种方法:

  1. 经典方式:将TTF或OTF文件放在/assets/fonts目录下,然后建一个Typeface with Typeface.createFromAsset(getAssets(), "fonts/custom.ttf").
  2. 从 API 26 开始原生,或者从 API 16 开始使用 AppCompat:create an XML font family by placing lowercased TTF/OTF files in res/font folder and then reference them directly in XML layouts with android:fontFamily="@font/custom", or access them programatically with ResourcesCompat.getFont(this, R.font.custom).

字体资源和资产之间需要牢记的主要区别是什么?

具体来说,它们是否以相同的方式呈现,它们中的任何一个在性能方面是否更快或更高效?

是否可以假设字体资源仅适用于 APK 中预打包的字体,而字体资源更灵活,因为您可以从 APK 内部或外部的任意文件创建字体?

更新: 经过一些实验后,字体资源似乎是在 AppWidget TextViews 中设置自定义字体而无需手动将它们绘制为位图的唯一方法,但这需要设备实际 运行 API 26(在这种特定情况下使用支持库没有帮助)。

Specifically, are they rendered in the same way, and is any of them faster or more efficient in terms of performance?

ResourcesCompat.getFont 是这样工作的:

  1. 如果我们已经将字体资源 ID 解析为 Typeface,请检查内存缓存。如果我们成功了,我们就完成了。
  2. 将资源复制到磁盘文件。
  3. 使用 Typerface.createFromFile 从文件创建 Typeface 并缓存它。

APK 中捆绑的字体也是如此。我不会深入探讨可下载字体的工作原理。您可以探索 in the docs or in the source.

两种方法都一样。他们从来源创建了一个 Typeface 对象。

一个关键区别:如果你直接使用Typeface API,你负责缓存。你不想加载多次使用相同的字体,因为每个 Typeface 实例都会占用大量内存。

过去,我使用 this code from Calligraphy 来处理从资产加载字体时的缓存。

After a bit of experimentation it looks like font resources are the only way to set custom fonts in AppWidget TextViews [...]

看来你是对的。通知和小部件(任何使用 RemoteViews 的东西)只能在视图上使用本机可用的资源和属性。

另请参阅:How to use a custom typeface in a widget?