亲测可行!
以下代码主要来源: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();
}
}