如何在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, 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();
}

最新更新