微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 Harmony Os 中为文本设置自定义字体样式,即设置一种未在 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,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();
    }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。