如何在 Harmony Os 中为文本设置自定义字体样式,即设置 Harmony OS 中未预先定义的新字体?

How to set a custom font style to a text in Harmony Os i.e setting a new font which is not pre defined in Harmony OS?

我想将文本组件 (dayTitle) 的字体样式更改为我的项目的自定义字体。对于设置预定义字体,例如:- BOLD,Harmony OS 平台允许用户以这种方式设置预定义字体 -

dateTitle.setFont(Font.DEFAULT_BOLD)

有什么方法可以为我的文本组件(dayTitle)设置自定义字体?

将您的自定义字体放入 resources/rawfile/ 并使用以下代码段从资源目录访问自定义字体,

    Font createFontBuild(Context context, String name) {
        ResourceManager resManager = context.getResourceManager();
        RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/" + name);
        Resource resource = null;
        try {
            resource = rawFileEntry.openRawFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuffer fileName = new StringBuffer(name);
        File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName.toString());
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
            int index;
            byte[] bytes = new byte[1024];
            while ((index = resource.read(bytes)) != -1) {
                outputStream.write(bytes, 0, index);
                outputStream.flush();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                resource.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        Font.Builder builder = new Font.Builder(file);
        return builder.build();
    }