自定义注册下载到沙箱cache中生僻字字体

自定义注册下载到沙箱cache中生僻字字体

HarmonyOS
2024-05-20 21:53:04
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
cbaby

有些需要录入的用户名是生僻字的场景,如果超出手机内置字体字符集的情况下,用户名不能正确的显示出来,这时候就需要根据该生僻字去动态请求存储生僻字字体的服务器,获取该生僻字的字体文件才能显示出来。

2.使用的核心API

@ohos.font

@ohos.request

3.核心代码解释

将网络生僻字字体文件下载到沙箱cache目录下面(之所以将字体下载到沙箱,是为给字体做缓存,便于下次快速展示,以及节省用户流量),然后进行注册使用。

import common from '@ohos.app.ability.common' 
import FileUtils from '../utils/FileUtils' 
import font from '@ohos.font' 
  
/** 
 * 自定义注册下载到沙箱cache中生僻字字体 
 */ 
@Entry 
@Component 
struct Index { 
  controller: TextInputController = new TextInputController() 
  fontFamily: string = 'HarmonyOS Sans' // 系统默认字体 
  fontFamily2: string = 'FZSong-RKXX'   // 自定义字体名称 
  context: Context = getContext(this) as common.UIAbilityContext 
  cacheDir: string = this.context.cacheDir; 
  // realCacheDir: string = '/data/app/el2/100/base/com.example.registercustomfontbycache/haps/entry/cache' // 可以使用hdc命令进入到该目录查看下载的字体文件 
  // 网络字体链接 
  // urlStr: string = "https://cdn8.foundertype.com/app/f57344dcb33fa9e4d0035e8257c6737a/FZSong-RKXX_32795052670000000000.ttf" // 字体链接失效了 
  // 测试字体库:https://gitcode.com/mirrors/ice-times/android-ttf-download/tree/master/%E5%AD%97%E4%BD%93 
  urlStr: string = "https://raw.gitcode.com/mirrors/ice-times/android-ttf-download/blobs/1a19b2b32e9de5bcf154db64ea7cac3245327c78/%E6%96%B9%E6%AD%A3%E5%8D%A1%E9%80%9A%E7%AE%80%E4%BD%93.ttf" 
  
  @State inputValue: string = "" 
  @State fontFamilyCurrent: string = this.fontFamily 
  @State isDownloadCompleted: boolean = false 
  
  build() { 
    Row() { 
      Column() { 
        Button('下载字体') 
          .margin(20) 
          .onClick(()=>{ 
            let fontFileDir = this.cacheDir + '/FZSong-RKXX.ttf' 
            console.log(`fontFileDir=${fontFileDir}`) 
            let flag = FileUtils.isFileExist(fontFileDir) 
            console.log(`flag=${flag}`) 
            if (FileUtils.isFileExist(fontFileDir)) { 
              AlertDialog.show({ 
                title: '提示', 
                message: '沙箱cache中字体文件已存在', 
                autoCancel: true 
              }) 
              return 
            } 
            const resultPromise = FileUtils.downloadNetworkFont(this.context, this.urlStr, 'internal://cache/FZSong-RKXX.ttf') 
            resultPromise.then((value: boolean) => { 
              if (value) { 
                this.cacheDir = this.context.cacheDir 
                this.isDownloadCompleted = value 
                AlertDialog.show({ 
                  title: '提示', 
                  message: '下载成功!', 
                  autoCancel: true 
                }) 
              } 
            }).catch((error: Error) => { 
              console.error(error.message) 
            }) 
          }) 
  
        Button('注册字体') 
          .margin({bottom:20}) 
          .onClick(()=>{ 
            if (this.isDownloadCompleted) { 
              console.info("点击注册字体") 
              font.registerFont({ familyName: this.fontFamily2, familySrc: 'file://' + this.context.cacheDir + '/FZSong-RKXX.ttf' }) 
              this.fontFamilyCurrent = this.fontFamily2; 
            } else { 
              AlertDialog.show({ 
                title: '提示', 
                message: '字体尚未下载完毕!', 
                autoCancel: true 
              }) 
            } 
          }) 
  
        TextInput({ controller: this.controller, text: this.inputValue }) 
          .onChange((value: string)=>{ 
            this.inputValue = value; 
          }) 
          .fontFamily(this.fontFamilyCurrent) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
} 
  
// FileUtils.ts 
import request from '@ohos.request'; 
import common from '@ohos.app.ability.common'; 
import { BusinessError } from '@ohos.base'; 
import fs from '@ohos.file.fs'; 
  
/** 
 * 下载网络字体 
 * @param context 上下文 
 * @param downloadLink 下载的网络字体链接 
 * @param saveDir 保存在沙箱cache中的路径 
 * @returns  Promise<boolean> 
 */ 
function downloadNetworkFont(context: common.Context, downloadLink: string, saveDir: string): Promise<boolean> { 
  return new Promise((resolve, reject) => { 
    let downloadTask: request.DownloadTask; 
    try { 
      request.downloadFile(context, { 
        url: downloadLink, 
        filePath: saveDir 
      }, (err: BusinessError, data: request.DownloadTask) => { 
        if (err) { 
          console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`); 
          reject(new Error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`)); 
        } 
        downloadTask = data; 
        downloadTask.on('progress', (receivedSize, totalSize) => { 
          console.info("cplog download receivedSize:" + receivedSize + " totalSize:" + totalSize); 
        }); 
        downloadTask.on('complete', ()=> { 
          resolve(true); 
        }) 
      }); 
    } catch (err) { 
      console.error(`Failed to request the download. err: ${JSON.stringify(err)}`); 
      reject(new Error(`Failed to request the download. err: ${JSON.stringify(err)}`)); 
    } 
  } 
  ); 
} 
  
/** 
 * 以同步方法检查文件是否存在 
 * @param path 
 * @returns 
 */ 
function isFileExist(path: string): boolean { 
  return fs.accessSync(path); 
} 
  
export default { 
  downloadNetworkFont, 
  isFileExist, 
}

6.适配的版本信息

IDE:DevEco Studio 4.1.3.220

SDK:4.0(API10)(HMS Core 4.0.0.42)(OpenHarmony 4.0.10.15)

分享
微博
QQ
微信
回复
2024-05-22 15:40:30
相关问题
注册自定义字体在 webview 中无效
776浏览 • 1回复 待解决
鸿蒙中如何自定义字体文件
17785浏览 • 1回复 待解决
如何使用和加载自定义字体
674浏览 • 1回复 待解决
Ark UI是否如何使用自定义字体
1872浏览 • 1回复 待解决
自定义弹窗自定义转场动画
382浏览 • 1回复 待解决
如何自定义Component 属性
13364浏览 • 3回复 待解决
如何访问自定义文件?
320浏览 • 1回复 待解决
hvigor自定义扩展demo
301浏览 • 1回复 待解决
自定义组件如何导出、引入?
819浏览 • 1回复 待解决
自定义子 window 大小限制
516浏览 • 1回复 待解决
如何设置自定义弹窗位置
661浏览 • 1回复 待解决
鸿蒙组件toast自定义样式
7164浏览 • 1回复 待解决
自定义构建任务写入文件
332浏览 • 1回复 待解决