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

想要在鸿蒙实现以下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
相关问题
如何在js文件引入自定义js文件
5001浏览 • 1回复 待解决
Ark UI是否如何使用自定义字体
634浏览 • 1回复 待解决
js 自定义组件如何传递方法?
3556浏览 • 2回复 待解决
如何自定义Component 属性
11493浏览 • 3回复 待解决
自定义组件嵌套子组件
6438浏览 • 3回复 待解决
鸿蒙组件toast自定义样式
5515浏览 • 1回复 待解决
智慧推荐可以自定义app吗
5005浏览 • 1回复 待解决
鸿蒙怎么实现自定义布局的Dialog
6241浏览 • 2回复 已解决
【求助】自定义相机Camera2焦距异常
5579浏览 • 1回复 待解决
JAVA卡片怎么用自定义组件?
3832浏览 • 1回复 待解决
华为手机是否支持自定义锁屏页面?
1623浏览 • 1回复 待解决