本示例介绍利用 上传下载 模块和 注册自定义字体 模块实现从网络上下载字体并注册应用字体的功能,该场景多用于由特殊字体要求的场景。

使用说明
本例的实现主要是调用下载接口下载字体文件并且注册到字体库,实现字体动态注册的功能。
1.在点击思源宋体按钮时,将会先检查沙箱中是否存在对应文件,若存在对应字体文件,则直接注册切换字体;若不存在对应字体文件,执行后续下载操作。
let res = fs.accessSync(filePath);
if (res) {
//字体注册
font.registerFont({
familyName: $r('app.string.font_SourceHanSerif'),
familySrc: DOWNLOADHEADER + filePath
})
this.targetFont = SOURCEHANSERIF;
return;
}欢迎大家关注公众号<程序猿百晓生>,可以了解到一下知识点。1.OpenHarmony开发基础
2.OpenHarmony北向开发环境搭建
3.鸿蒙南向开发环境的搭建
4.鸿蒙生态应用开发白皮书V2.0 & V3.0
5.鸿蒙开发面试真题(含参考答案)
6.TypeScript入门学习手册
7.OpenHarmony 经典面试题(含参考答案)
8.OpenHarmony设备开发入门【最新版】
9.沉浸式剖析OpenHarmony源代码
10.系统定制指南
11.【OpenHarmony】Uboot 驱动加载流程
12.OpenHarmony构建系统--GN与子系统、部件、模块详解
13.ohos开机init启动流程
14.鸿蒙版性能优化指南
.......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 // 动态切换字体页面及具体逻辑如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。