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

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

 

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

 

鸿蒙中找到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();
}

 

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

 

resources/rawfile/fonts/huakangshaonv.ttf

 

分享
微博
QQ
微信
回复2
2021-04-27 18:31:05
相关问题
如何使用和加载自定义字体
149浏览 • 1回复 待解决
注册的自定义字体在 webview 无效
178浏览 • 1回复 待解决
Ark UI是否如何使用自定义字体
1177浏览 • 1回复 待解决
如何在js文件引入自定义js文件
5736浏览 • 1回复 待解决
ArkTS如何自定义资源文件
319浏览 • 1回复 待解决
自定义组件如何添加图片?
748浏览 • 1回复 待解决
如何自定义弹窗再次弹窗
187浏览 • 1回复 待解决
自定义资源文件怎么读取?
269浏览 • 1回复 待解决
自定义弹窗的变量如何传递给页面
369浏览 • 1回复 待解决
ArkTs如何自定义容器组件?
954浏览 • 1回复 待解决
鸿蒙组件toast自定义样式
6639浏览 • 1回复 待解决
如何理解自定义弹窗的gridCount参数
354浏览 • 1回复 待解决
如何自定义Component 属性
12930浏览 • 3回复 待解决
js 自定义组件如何传递方法?
4217浏览 • 2回复 待解决
如何设置自定义组件height缺省
137浏览 • 1回复 待解决
如何设置自定义弹窗位置
226浏览 • 1回复 待解决
自定义组件如何导出、引入?
365浏览 • 1回复 待解决