代码拉取完成,页面将自动刷新
本示例介绍利用上传下载 模块和注册自定义字体模块实现从网络上下载字体并注册应用字体的功能,该场景多用于由特殊字体要求的场景。
使用说明
本例的实现主要是调用下载接口下载字体文件并且注册到字体库,实现字体动态注册的功能。
本例中代码详情可参考FontDynamicRegistration.ets
1.在点击思源宋体按钮时,将会先检查沙箱中是否存在对应文件,若存在对应字体文件,则直接注册切换字体;若不存在对应字体文件,执行后续下载操作。
let res = fs.accessSync(filePath);
if (res) {
//字体注册
font.registerFont({
familyName: $r('app.string.font_SourceHanSerif'),
familySrc: DOWNLOADHEADER + filePath
})
this.targetFont = SOURCEHANSERIF;
return;
}
2.若沙箱内没有对应的字体,则会启动下载任务,将字体文件下载到沙箱内并注册应用。
try {
// TODO :知识点:下载网络文件
request.downloadFile(getContext(), {
url: URL,
filePath: filePath
}, (err, downloadTask) => {
if (err) {
logger.error('Failed to request the download. Cause: ' + JSON.stringify(err));
return;
}
// 监听下载进度,赋值到状态变量
downloadTask.on('progress', (receivedSize, totalSize) => {
this.progressFlag = true;
this.downloadNow = receivedSize;
this.downloadTotal = totalSize;
logger.info("Download receivedSize:" + receivedSize + " totalSize:" + totalSize);
});
// 监听下载完成事件
downloadTask.on('complete', () => {
this.progressFlag = false;
this.downloadButtonText = SOURCE_HAN_SERIF;
this.downloadButtonEnabled = true;
try {
promptAction.showToast({
message: $r('app.string.toast_message'),
duration: TOAST_DURATION
});
} catch (error) {
const message = (error as BusinessError).message;
const code = (error as BusinessError).code;
logger.error(`showToast args error code is ${code}, message is ${message}`);
}
downloadTask.off('progress');
downloadTask.off('fail');
font.registerFont({
familyName: $r('app.string.font_SourceHanSerif'),
familySrc: DOWNLOAD_HEADER + filePath
})
this.targetFont = SOURCE_HAN_SERIF;
})
// 监听下载失败事件
downloadTask.on('fail', (err: number) => {
logger.info("DownloadTask failed");
let res = fs.accessSync(filePath);
if (res) {
fs.unlink(filePath);
downloadTask.off('fail');
}
})
});
} catch (err) {
logger.info("Download failed with error message: " + err.message + ", error code: " + err.code);
}
不涉及
fontdynamicregistration // har类型
|---src/main/ets/components
| |---FontDynamicRegistration.ets // 动态切换字体页面及具体逻辑
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。