我们如何从可下载的字体创建字体?

How can we create a typeface from a downloadable font?

我有一个辅助方法可以执行以下操作:

public CustomTypefaceSpan(Context context, String typefaceName) {
    mTypeface = sTypefaceCache.get(typefaceName);

    if (mTypeface == null) {
        mTypeface = Typeface.createFromAsset(context.getApplicationContext().getAssets(),
                String.format("fonts/%s", typefaceName));

        // Cache the loaded Typeface
        sTypefaceCache.put(typefaceName, mTypeface);
    }
}

切换到可下载字体后,我们收到以下异常,因为资产文件夹中没有可用字体。我们如何使用可下载的字体执行此操作?谢谢!

原因:java.lang.RuntimeException:未找到字体资源 fonts/OpenSans-Regular.ttf 在 android.graphics.Typeface.createFromAsset(Typeface.java:206) 在 com.woot.util.ui.CustomTypefaceSpan.(CustomTypefaceSpan.java:19) 在 com.woot.util.ui.ActivityUtil.setTitleCustomFont(ActivityUtil.java:20) 在 com.woot.storelocator.selectstorelanding.SelectStoreActivity.onCreate(SelectStoreActivity.java:40) 在 android.app.Activity.performCreate(Activity.java:6664) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 在 android.app.ActivityThread.-wrap12(ActivityThread.java) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:154) 在 android.app.ActivityThread.main(ActivityThread.java:6077) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

以下示例代码说明了整个可下载字体过程:

 FontRequest request = new FontRequest("com.example.fontprovider.authority",
            "com.example.fontprovider", "my font", certs); 
    FontsContract.FontRequestCallback callback =
        new FontsContract.FontRequestCallback() { 
            @Override 
            public void onTypefaceRetrieved(Typeface typeface) {
                // Your code to use the font goes here 
                ... 
            } 

            @Override 
            public void onTypefaceRequestFailed(int reason) {
                // Your code to deal with the failure goes here 
                ... 
            } 
    }; 
FontsContract.requestFonts(context, request, callback , handler);