鸿蒙HarmonyOS NEXT在Har包中播放Lottie的问题

586 阅读2分钟

在HarmonyOS NEXT中,Lottie资源可以放到Entry所在目录下,这样系统默认的获取资源的方法都能读取到。

this.animateItem2 = lottie.loadAnimation({
  container: this.canvasRenderingContext,
  renderer: 'canvas', // canvas 渲染模式
  loop: true,
  autoplay: true,
  name: '2016',
  contentMode: 'Contain',
  path: "common/lottie/red_heart.json", // 路径加载动画只支持entry/src/main/ets 文件夹下的相对路径
  // path: "common/lottie/data_rawfile.json"
  // path: "common/lottie/data_base64.json"
})

但在Har包中的Lottie资源也不适合全部放到Entry中,当放到Har包对应的rawfile文件夹下,没办法获取到文件路径。
PS:尝试很多办法,也和华为官方提了很多工单,如果各位读者有好的办法,欢迎提供参考。
鸿蒙该问题的工单:
developer.huawei.com/consumer/cn…
developer.huawei.com/consumer/cn…

经过一番摸索,发现Lottie还支持直接加载JSON的方式播放动画,参数Key是animationData。 那么尝试摸索加载Lottie动画文件,并转成JSON解决该问题。
此时参考这个项目:gitee.com/openharmony…
在该项目的sharedLibrary/index.ets中有关于animationData参数使用的实例代码。 这个项目的实例代码在做JSON转换的时候用了一些废弃的API,但提供了思路,于是挨个排查替代的API,最终在HarmonyOS NEXT Beta2系统上跑通了。
代码如下:
引入util和JSON

import util from '@ohos.util';
import { JSON } from '@kit.ArkTS';

创建Lottie的代码:

let context = getContext(this); // 获取Context
let resourceManager = context.resourceManager; // 获取Context下的resourceManager
let inAniamtionData = resourceManager.getRawFileContentSync("LottieAnimation/idle/data.json") // 获取Har包下rawfile文件夹下Lottie的文件流,Uint8Array类型
let resStr = util.TextDecoder.create('utf-8',{ignoreBOM: true}) //设置解码器
let lottieStr = resStr.decodeWithStream(inAniamtionData) // 将文件流解码成字符串
let lottieData = JSON.parse(lottieStr) // 解析成JSON二进制

this.rocketInAnimation = lottie.loadAnimation({
  container: this.canvasRenderingContext,
  renderer: 'canvas', // canvas选软模式
  loop: true,
  autoplay: true,
  name:'rocketInAnimation',
  animationData: lottieData // 将动画的JSON传递给Lottie,完成动画的创建
})

加载画布

build() {
  Column() {
    Canvas(this.canvasRenderingContext)
      .width('100%')
      .height('100%')
  }
  .width('100%')
  .height('100%')
}

Lottie成功加载

参考资料: developer.huawei.com/consumer/cn…