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

想要在鸿蒙实现以下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
相关问题
如何使用和加载自定义字体
943浏览 • 1回复 待解决
注册的自定义字体在 webview 无效
1007浏览 • 1回复 待解决
如何在js文件引入自定义js文件
6401浏览 • 1回复 待解决
Ark UI是否如何使用自定义字体
2080浏览 • 1回复 待解决
如何访问自定义文件
373浏览 • 1回复 待解决
ArkTS如何自定义资源文件
944浏览 • 1回复 待解决
自定义组件如何添加图片?
1326浏览 • 1回复 待解决
自定义构建任务写入文件
384浏览 • 1回复 待解决
如何自定义弹窗再次弹窗
1146浏览 • 1回复 待解决
自定义弹窗自定义转场动画
469浏览 • 1回复 待解决
自定义资源文件怎么读取?
978浏览 • 1回复 待解决
鸿蒙组件toast自定义样式
7427浏览 • 1回复 待解决
如何理解自定义弹窗的gridCount参数
1008浏览 • 1回复 待解决
自定义弹窗的变量如何传递给页面
1189浏览 • 1回复 待解决