当前位置:   article > 正文

HarmonyOS应用开发-闪屏启动页

HarmonyOS应用开发-闪屏启动页

        这是鸿蒙开发者网站的一个应用《溪村小镇》示例代码,把闪屏启动页单拿出来,分析一下代码。

一、先上效果图

这是应用打开时的一个启动页,启动页会根据三个时间段(白天、傍晚、晚上)来分别展示溪村小镇不同的景色。

二、实现方法:

1.在pages页面下新建一个页面命名为“Splash”,Splash页面的代码在下面展示。

2.然后在onWindowStageCreate生命周期中配置启动页入口,可以看到“pages/Splash”为启动页入口:

  1. // EntryAbility.ets
  2. onWindowStageCreate(windowStage: window.WindowStage) {
  3. // 设置沉浸式窗口,背景透明
  4. const windowBarMag = new WindowBarManager();
  5. windowBarMag.immersiveWindow(windowStage, Const.TRANSPARENT_COLOR, true);
  6. // 加载启动页内容
  7. windowStage.loadContent('pages/Splash', (err, data) => {
  8. if (err.code) {
  9. hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
  10. return;
  11. }
  12. hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
  13. });
  14. }
  • WindowBarManager用于管理窗口样式,这里设置了沉浸式窗口,并将背景设为透明。
  • 通过windowStage.loadContent加载启动页的内容,路径为'pages/Splash'。

        启动页会在aboutToAppear生命周期内初始化轮播图片资源及定时任务,会展示5秒溪村的优美风景,用户可以点击右上角的跳过直接进入应用主页,也可以等5秒结束自动进入应用主页;5秒倒计时结束、用户主动点击跳过或启动页面销毁时都会取消定时器任务。

启动页的代码如下,代码分析在下面:

  1. import router from '@ohos.router';
  2. import { CommonConstants as Const } from '../common/constants/CommonConstants';
  3. import { splashImages } from '../viewmodel/SplashModel';
  4. @Entry
  5. @Component
  6. struct Splash {
  7. private swiperController: SwiperController = new SwiperController();
  8. private data: Resource[]
  9. @State showSwiper: boolean = false;
  10. @State countdown: number = Const.COUNTDOWN;
  11. private timer: number = -1;
  12. // 在此生命周期内根据当前时间段分配轮播展示的溪村小镇风景图
  13. aboutToAppear(): void {
  14. let hours = new Date().getHours();
  15. if (hours >= Const.MORNING_TIME && hours < Const.EVENING_TIME) {
  16. this.data = splashImages.day;
  17. } else if (hours >= Const.EVENING_TIME && hours <= Const.NIGHT_TIME) {
  18. this.data = splashImages.dusk;
  19. } else {
  20. this.data = splashImages.night;
  21. }
  22. // 启动画面展示3秒后 轮播展示溪村小镇风景
  23. setTimeout(() => {
  24. this.showSwiper = true;
  25. this.startTiming();
  26. }, Const.SPLASH_DURATION)
  27. }
  28. // 轮播展示溪村小镇风景倒计时5秒
  29. startTiming() {
  30. this.timer = setInterval(() => {
  31. this.countdown--;
  32. if (this.countdown === 0) {
  33. this.clearTiming();
  34. // 5秒钟后自动跳转到应用首页
  35. this.jumpToMainPage();
  36. }
  37. }, Const.DURATION);
  38. }
  39. // 清理定时器
  40. clearTiming() {
  41. if (this.timer !== -1) {
  42. clearInterval(this.timer);
  43. this.timer = -1;
  44. }
  45. }
  46. // 跳转到应用首页
  47. jumpToMainPage() {
  48. this.clearTiming();
  49. router.replaceUrl({
  50. url: 'pages/Index'
  51. });
  52. }
  53. // 页面销毁时清理定时器
  54. aboutToDisappear() {
  55. this.clearTiming();
  56. }
  57. build() {
  58. Column() {
  59. Stack() {
  60. // 轮播展示溪村小镇风景
  61. if (this.showSwiper) {
  62. Swiper(this.swiperController) {
  63. ForEach(this.data, (item: Resource) => {
  64. Image(item)
  65. .width(Const.FULL_SIZE)
  66. .height(Const.FULL_SIZE)
  67. .objectFit(ImageFit.Cover)
  68. })
  69. }
  70. .loop(true)
  71. .interval(2 * Const.DURATION)
  72. .duration(Const.DURATION)
  73. .autoPlay(true)
  74. .indicatorStyle({
  75. bottom: $r('app.float.100'),
  76. color: $r('app.color.swiper_dot_color')
  77. })
  78. .curve(Curve.Linear)
  79. .onChange((index: number) => {
  80. console.info(index.toString())
  81. })
  82. // 轮播倒计时,点击可进入应用主页
  83. Text() {
  84. Span($r('app.string.skip'))
  85. Span(`${this.countdown}`)
  86. }
  87. .onClick(() => this.jumpToMainPage())
  88. .fontColor(Color.White)
  89. .fontSize($r('app.float.12fp'))
  90. .backgroundColor($r('app.color.swiper_jump_bg_color'))
  91. .width($r('app.float.63'))
  92. .height($r('app.float.24'))
  93. .borderRadius($r('app.float.10'))
  94. .textAlign(TextAlign.Center)
  95. .position({
  96. x: Const.PERCENTAGE_78,
  97. y: $r('app.float.35')
  98. })
  99. } else { // 应用启动画面
  100. Image($r('app.media.splash_bg'))
  101. .width(Const.FULL_PERCENT)
  102. .height(Const.FULL_PERCENT)
  103. Image($r('app.media.ic_splash'))
  104. .width($r('app.float.192'))
  105. .height($r('app.float.192'))
  106. .offset({
  107. y: `-${Const.PERCENTAGE_15}`
  108. })
  109. .objectFit(ImageFit.Contain)
  110. Column() {
  111. Text(Const.SPLASH_DES)
  112. .fontColor(Color.White)
  113. .fontSize($r('app.float.font_size_24fp'))
  114. .fontWeight(FontWeight.Medium)
  115. Text(Const.SPLASH_WELCOME)
  116. .fontSize($r('app.float.font_size_16fp'))
  117. .fontColor(Color.White)
  118. .margin({
  119. top: $r('app.float.5')
  120. })
  121. }
  122. .offset({
  123. y: Const.PERCENTAGE_25
  124. })
  125. }
  126. }
  127. }
  128. .height(Const.FULL_SIZE)
  129. .width(Const.FULL_SIZE)
  130. }
  131. }

让我来对这段代码进行详细的解释:

  1. 导入模块:

    1. import router from '@ohos.router';
    2. import { CommonConstants as Const } from '../common/constants/CommonConstants';
    3. import { splashImages } from '../viewmodel/SplashModel';

    这里导入了一些模块和常量,其中 router 模块用于导航,CommonConstants 包含了一些常量,Const是它的别名,在代码中就可以用Const.COUNTDOWN来使用其COUNTDOWN常量了,splashImages 包含了一些溪村小镇风景图的资源。

  2. 组件定义:

    1. @Entry
    2. @Component
    3. struct Splash {

    使用 HarmonyOS 提供的注解 @Entry@Component 定义了一个名为 Splash 的组件结构。

  3. 私有变量和状态:

    1. private swiperController: SwiperController = new SwiperController();
    2. private data: Resource[];
    3. @State showSwiper: boolean = false;
    4. @State countdown: number = Const.COUNTDOWN;
    5. private timer: number = -1;

    在组件结构中定义了一些私有变量和状态,其中包括一个用于控制轮播的 swiperController,一个存储资源的数组 data,以及控制页面状态的变量和计时器。

  4. 生命周期函数 aboutToAppear

    1. // 在此生命周期内根据当前时间段分配轮播展示的溪村小镇风景图
    2. aboutToAppear(): void {
    3. //获取当前的时间:几点钟
    4. let hours = new Date().getHours();
    5. //大于6点并且小于18点,属于白天
    6. if (hours >= Const.MORNING_TIME && hours < Const.EVENING_TIME) {
    7. this.data = splashImages.day;
    8. } else if (hours >= Const.EVENING_TIME && hours <= Const.NIGHT_TIME) {//大于18点小于19点,属于黄昏
    9. this.data = splashImages.dusk;
    10. } else {//其他时间就是晚上了
    11. this.data = splashImages.night;
    12. }
    13. // 启动画面展示3秒后 轮播展示溪村小镇风景
    14. setTimeout(() => {
    15. this.showSwiper = true;
    16. this.startTiming();
    17. }, Const.SPLASH_DURATION)
    18. }

    在组件即将显示的生命周期内,根据当前时间段分配溪村小镇风景图,并设置定时器,在一定时间后展示轮播图。

  5. 定时器函数 startTimingclearTiming

    1. startTiming() {
    2. this.timer = setInterval(() => {
    3. this.countdown--;
    4. if (this.countdown === 0) {
    5. this.clearTiming();
    6. this.jumpToMainPage();
    7. }
    8. }, Const.DURATION);
    9. }
    10. clearTiming() {
    11. if (this.timer !== -1) {
    12. clearInterval(this.timer);
    13. this.timer = -1;
    14. }
    15. }

    这两个函数用于启动和清理倒计时定时器。

  6. 页面跳转函数 

    1. jumpToMainPage() {
    2. this.clearTiming();
    3. router.replaceUrl({
    4. url: 'pages/MainPage'
    5. });
    6. }

             使用系统提供的router组件,用于页面跳转到应用首页,并在跳转前清理定时器。其中router.replaceUrl代表用下一个页面代替当前页,当前页会被销毁,进入到下一页之后如果按返回键也是不能返回到启动页的。                                                                                         此外router还有router.pushUrl方法可以保存当前页并跳转到下一页,router.back返回上一页面或指定的页面,router.clear清空页面栈中的所有历史页面,仅保留当前页面作为栈顶页面等方法。

  7. 生命周期函数 aboutToDisappear

    1. aboutToDisappear() {
    2. this.clearTiming();
    3. }

    在组件即将销毁的生命周期内清理定时器。

  8. 页面构建函数 build

    build() { // ... }

    构建页面的函数,使用 HarmonyOS 提供的组件和样式语法构建了页面的布局和样式。

        总体来说,这段代码实现了一个具有定时展示溪村小镇风景的启动画面,包括轮播图、倒计时和页面跳转等功能。在页面的构建函数中使用了 HarmonyOS 提供的组件和样式语法来定义页面的结构和样式。

代码地址:Codelabs: 分享知识与见解,一起探索HarmonyOS的独特魅力。 - Gitee.com

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/31360
推荐阅读
  

闽ICP备14008679号