鸿蒙中如何自定义字体文件

想要在鸿蒙实现以下Android平台的功能

 

//设置字体
setTypeface(typeface)
//使用自定义字体文件
Typeface.createFromAsset(getAssets(), typefacePath)
  • 1.
  • 2.
  • 3.
  • 4.

 

鸿蒙中找到setFont方法,但是Font该如何从文件创建

字体
Font
Typeface
2021-04-26 17:08:15
浏览
1
收藏 0
回答 1
回答 1
按赞同
/
按时间
没用的喵叔
4

亲测可行!

 

以下代码主要来源:https://gitee.com/chinasoft_ohos/RTextView

Text text  = (Text) findComponentById(ResourceTable.Id_text);
try {
    setTypeface(MainAbilitySlice.this, text, "huakangshaonv.ttf");
} catch (IOException e) {
    e.printStackTrace();
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

 

public static void setTypeface(Context context, Text text, String typeface) throws IOException {
    if (TextTool.isNullOrEmpty(typeface)) {
        return;
    }

    File file = new File(context.getCodeCacheDir(), typeface);
    OutputStream outputStream = null;
    ResourceManager resManager = context.getResourceManager();
    RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/fonts/" + typeface);

    Resource resource = null;
    try {
        resource = rawFileEntry.openRawFile();

        outputStream = new FileOutputStream(file);
        int index;
        byte[] bytes = new byte[1024];
        if (resource != null) {
            while ((index = resource.read(bytes)) != -1) {
                outputStream.write(bytes, 0, index);
                outputStream.flush();
            }
            Font.Builder builder = new Font.Builder(file);
            Font font = builder.build();
            text.setFont(font);
        }
    } catch (FileNotFoundException | NullPointerException ignored) {
    } finally {
        resource.close();
        outputStream.close();
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.

 

resources/rawfile/fonts/huakangshaonv.ttf

 

分享
微博
QQ
微信
回复2
2021-04-27 18:31:05
相关问题
ArkUI如何使用自定义字体
1875浏览 • 2回复 待解决
如何自定义字体替换系统字体
1038浏览 • 1回复 待解决
HarmonyOS 如何设置自定义字体
1529浏览 • 1回复 待解决
HarmonyOS 全局自定义字体
728浏览 • 1回复 待解决
HarmonyOS 全局自定义字体
777浏览 • 1回复 待解决
如何使用和加载自定义字体
2871浏览 • 1回复 待解决
HarmonyOS 使用自定义字体
950浏览 • 1回复 待解决
HarmonyOS 自定义字体绘制
881浏览 • 1回复 待解决
注册的自定义字体在 webview 无效
2882浏览 • 1回复 待解决
Ark UI是否如何使用自定义字体
3707浏览 • 1回复 待解决
如何在js文件引入自定义js文件
8454浏览 • 1回复 待解决
如何访问自定义文件
1127浏览 • 1回复 待解决
HarmonyOS 能否默认使用自定义字体
479浏览 • 1回复 待解决
HarmonyOS 全局设置自定义字体的方法
703浏览 • 1回复 待解决
HarmonyOS RN 项目中使用自定义字体
743浏览 • 1回复 待解决
ArkTS如何自定义资源文件
2905浏览 • 1回复 待解决